from flask import Blueprint, request, jsonify
from ..models import User, Device, Admin, db # 确保 Admin 也已导入
from ..utils import validate_user_id, admin_required, log_admin_operation
from ..database import mongo_collection
from ..config import Config
from sqlalchemy import desc
import bcrypt
from datetime import datetime, timedelta # 在这里添加 timedelta
import pymysql
import jwt # 确保 jwt 已导入
import json # 用于手动构建JSON响应
from ..utils.ip_utils import get_client_ip

admin_bp = Blueprint('admin', __name__)

def normalize_user_id(user_id):
    """
    标准化用户ID，处理不同格式的ID
    - 如果是字符串但可以转为整数，返回整数形式
    - 如果是其他类型，尝试转为字符串
    - 返回元组 (字符串ID, 整数ID或None)
    """
    str_id = None
    int_id = None
    
    # 处理各种类型的ID
    if user_id is None:
        return None, None
        
    # 如果是整数
    if isinstance(user_id, int):
        str_id = str(user_id)
        int_id = user_id
    # 如果是字符串
    elif isinstance(user_id, str):
        str_id = user_id
        # 尝试转换为整数
        try:
            if user_id.isdigit():
                int_id = int(user_id)
        except (ValueError, TypeError):
            pass
    # 其他类型
    else:
        try:
            str_id = str(user_id)
            try:
                int_id = int(str_id)
            except (ValueError, TypeError):
                pass
        except:
            pass
            
    return str_id, int_id

@admin_bp.route('/v1/admin/userdata', methods=['GET'])
@admin_required
def get_all_users(admin_id, admin_level):
    """
    获取所有用户信息的接口，支持分页
    请求示例：/api/v1/admin/userdata?size=10&page=1
    
    参数说明：
    - page: 页码，默认为1
    - size: 每页记录数，默认为10
    
    返回格式：
    {
        "code": 0,
        "message": "获取用户列表成功",
        "data": {
            "total": 总用户数,
            "page": 当前页码,
            "size": 每页记录数,
            "total_pages": 总页数,
            "users": [用户列表]
        }
    }
    """
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        
        # 验证分页参数
        if page < 1 or size < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query",
                details={"page": page, "size": size},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="页码和每页数量必须为正整数"
            ), 400
        
        # 查询用户总数
        total_users = User.query.count()
        
        # 计算总页数
        total_pages = (total_users + size - 1) // size if total_users > 0 else 0
        
        # 查询用户数据（按注册时间降序排列）
        users = User.query.order_by(desc(User.register_at)).paginate(
            page=page, per_page=size, error_out=False
        )
        
        # 构建用户列表
        user_list = []
        for user in users.items:
            user_data = {
                "user_id": user.user_id,
                "user_name": user.user_name,
                "phonenumber": user.phonenumber,
                "register_at": user.register_at.strftime("%Y-%m-%d %H:%M:%S") if user.register_at else None
            }
            user_list.append(user_data)
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取用户列表成功",
            "data": {
                "total": total_users,
                "page": page,
                "size": size,
                "total_pages": total_pages,
                "users": user_list
            }
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query",
            details={"page": page, "size": size, "total": total_users},
            status="success",
            resource_type="users",
            resource_id=None
        )
        
        return jsonify(response), 200
        
    except Exception as e:
        # 记录错误日志
        print(f"[SYSTEM ERROR] 获取用户列表异常: {str(e)}")
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query",
            details={"error": str(e)},
            status="failed",
            resource_type="users",
            resource_id=None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/devices', methods=['GET'])
@admin_required
def get_all_devices(admin_id, admin_level):
    """
    获取所有设备信息的接口，支持分页
    请求示例：/api/v1/admin/devices?size=10&page=1
    或者：/api/v1/admin/devices?page_size=10&page=1
    
    参数说明：
    - page: 页码，默认为1
    - size/page_size: 每页记录数，默认为10（两者均支持，优先使用page_size）
    
    返回格式：
    {
        "code": 0,
        "message": "获取设备列表成功",
        "data": {
            "total": 总设备数,
            "page": 当前页码,
            "size": 每页记录数,
            "total_pages": 总页数,
            "devices": [设备列表]
        }
    }
    """
    try:
        print("[INFO] 开始处理获取设备列表请求")
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        # 同时支持size和page_size参数，优先使用page_size
        page_size = request.args.get('page_size')
        size = request.args.get('size')
        
        # 确定使用哪个参数
        if page_size is not None:
            print(f"[INFO] 使用page_size参数: {page_size}")
            size_value = int(page_size)
        elif size is not None:
            print(f"[INFO] 使用size参数: {size}")
            size_value = int(size)
        else:
            print("[INFO] 未提供size或page_size参数，使用默认值10")
            size_value = 10
        
        # 验证分页参数
        if page < 1 or size_value < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query",
                details={"page": page, "size": size_value},
                status="failed",
                resource_type="devices",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="页码和每页数量必须为正整数"
            ), 400
        
        print(f"[INFO] 分页参数: page={page}, size={size_value}")
        
        # 查询设备总数 - 使用简单的count查询避免查询模型中可能不存在的字段
        try:
            total_devices = db.session.query(db.func.count(Device.device_id)).scalar()
            print(f"[INFO] 设备总数: {total_devices}")
        except Exception as e:
            print(f"[ERROR] 设备总数查询异常: {str(e)}")
            import traceback
            traceback.print_exc()
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query",
                details={"error": str(e)},
                status="failed",
                resource_type="devices",
                resource_id=None
            )
            return jsonify(
                code=50001,
                message=f"设备总数查询异常: {str(e)}"
            ), 500
        
        # 计算总页数
        total_pages = (total_devices + size_value - 1) // size_value if total_devices > 0 else 0
        
        # 查询设备数据 - 仅选择数据库中确定存在的字段
        try:
            # 使用手动分页而不是ORM的paginate，以便更精确地控制查询字段
            query = db.session.query(
                Device.device_id,
                Device.device_key,
                Device.user_id,
                Device.create_at
            ).order_by(desc(Device.create_at))
            
            # 执行手动分页
            offset_val = (page - 1) * size_value
            devices = query.offset(offset_val).limit(size_value).all()
            print(f"[INFO] 查询到设备数量: {len(devices)}")
        except Exception as e:
            print(f"[ERROR] 设备分页查询异常: {str(e)}")
            import traceback
            traceback.print_exc()
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query",
                details={"error": str(e)},
                status="failed",
                resource_type="devices",
                resource_id=None
            )
            return jsonify(
                code=50001,
                message=f"设备查询异常: {str(e)}"
            ), 500
        
        # 构建设备列表
        device_list = []
        
        # 预先获取所有设备的最新状态
        device_statuses = {}
        try:
            device_ids = [device.device_id for device in devices]
            with mongo_collection(Config.MONGODB_COLLECTIONS.get("device_status", "device_status")) as collection:
                # 一次性查询所有设备的最新状态
                pipeline = [
                    {"$match": {"device_id": {"$in": device_ids}}},
                    {"$sort": {"timestamp": -1}},
                    {"$group": {
                        "_id": "$device_id",
                        "latest_status": {"$first": "$$ROOT"}
                    }}
                ]
                status_results = collection.aggregate(pipeline)
                
                for result in status_results:
                    device_id = result["_id"]
                    latest_status = result["latest_status"]
                    device_statuses[device_id] = latest_status
                
                print(f"[INFO] 预加载了 {len(device_statuses)} 个设备的状态信息")
        except Exception as e:
            print(f"[WARNING] 批量获取设备状态异常: {str(e)}")
        
        for device in devices:
            try:
                print(f"[INFO] 处理设备: {device.device_id}")
                # 默认设置激活状态为False
                is_activated = False
                
                # 获取设备状态
                device_status = None
                
                # 从预加载的状态中获取
                if device.device_id in device_statuses:
                    status = device_statuses[device.device_id]
                    device_status = {
                        "power": status.get("power", {}),
                        "network": status.get("network", {}),
                        "audio": status.get("audio", {})
                    }
                    # 从MongoDB中获取激活状态
                    activation_status = status.get("activation_status")
                    if activation_status == "ACTIVATED":
                        is_activated = True
                else:
                    # 如果预加载中没有，单独查询
                    try:
                        with mongo_collection(Config.MONGODB_COLLECTIONS.get("device_status", "device_status")) as collection:
                            status = collection.find_one(
                                {"device_id": device.device_id},
                                sort=[("timestamp", -1)]
                            )
                            if status:
                                device_status = {
                                    "power": status.get("power", {}),
                                    "network": status.get("network", {}),
                                    "audio": status.get("audio", {})
                                }
                                # 从MongoDB中获取激活状态
                                activation_status = status.get("activation_status")
                                if activation_status == "ACTIVATED":
                                    is_activated = True
                    except Exception as e:
                        print(f"[WARNING] 获取设备状态异常: {str(e)}, 设备ID: {device.device_id}")
                        device_status = {"error": "无法获取设备状态"}
                
                # 获取关联的用户信息，增加错误处理
                user_info = None
                if device.user_id:
                    try:
                        user = User.query.get(device.user_id)
                        if user:
                            user_info = {
                                "user_id": user.user_id,
                                "user_name": user.user_name
                            }
                    except Exception as e:
                        print(f"[WARNING] 获取用户信息异常: {str(e)}, 用户ID: {device.user_id}")
                        user_info = {"error": "无法获取用户信息"}
                
                device_data = {
                    "device_id": device.device_id,
                    "device_key": device.device_key,
                    "user": user_info,
                    "create_at": device.create_at.strftime("%Y-%m-%d %H:%M:%S") if device.create_at else None,
                    "status": device_status,
                    "is_activated": is_activated
                }
                device_list.append(device_data)
                print(f"[INFO] 设备 {device.device_id} 处理完成")
            except Exception as e:
                print(f"[WARNING] 处理设备数据异常: {str(e)}, 设备ID: {device.device_id}")
                import traceback
                traceback.print_exc()
                # 添加一个带有错误信息的设备条目，而不是完全跳过
                device_list.append({
                    "device_id": device.device_id if hasattr(device, "device_id") else "未知",
                    "error": f"处理设备数据异常: {str(e)}"
                })
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取设备列表成功",
            "data": {
                "total": total_devices,
                "page": page,
                "size": size_value,
                "total_pages": total_pages,
                "devices": device_list
            }
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query",
            details={"page": page, "size": size_value, "total": total_devices},
            status="success",
            resource_type="devices",
            resource_id=None
        )
        
        print("[INFO] 设备列表请求处理完成")
        return jsonify(response), 200
        
    except Exception as e:
        # 记录错误日志
        print(f"[SYSTEM ERROR] 获取设备列表异常: {str(e)}")
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query",
            details={"error": str(e)},
            status="failed",
            resource_type="devices",
            resource_id=None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/banuser', methods=['POST'])
@admin_required
def ban_user(admin_id, admin_level):
    """
    禁用用户账号接口
    请求示例：/api/v1/admin/banuser?user_id=123&user_name=张三&phonenumber=13800138000
    
    参数说明（至少需要提供一个参数）：
    - user_id: 用户ID
    - user_name: 用户名
    - phonenumber: 手机号
    
    返回格式：
    {
        "code": 0,
        "message": "禁用用户成功",
        "data": {
            "affected_users": 被禁用的用户数量
        }
    }
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        user_name = request.args.get('user_name')
        phonenumber = request.args.get('phonenumber')
        
        # 验证至少提供了一个查询参数
        if not any([user_id, user_name, phonenumber]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="ban_user",
                details={"error": "未提供查询参数"},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="请至少提供一个查询参数：用户ID、用户名或手机号"
            ), 400
        
        # 构建查询条件
        query = User.query
        if user_id:
            query = query.filter(User.user_id == user_id)
        if user_name:
            query = query.filter(User.user_name == user_name)
        if phonenumber:
            query = query.filter(User.phonenumber == phonenumber)
        
        # 查询符合条件的用户
        users = query.all()
        
        # 检查是否找到用户
        if not users:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="ban_user",
                details={
                    "user_id": user_id,
                    "user_name": user_name,
                    "phonenumber": phonenumber,
                    "error": "未找到符合条件的用户"
                },
                status="failed",
                resource_type="users",
                resource_id=user_id if user_id else None
            )
            return jsonify(
                code=40400,
                message="未找到符合条件的用户"
            ), 404
        
        # 禁用用户账号
        affected_count = 0
        affected_users = []
        for user in users:
            user.is_active = False
            affected_count += 1
            affected_users.append({
                "user_id": user.user_id,
                "user_name": user.user_name,
                "phonenumber": user.phonenumber
            })
        
        # 提交数据库更改
        db.session.commit()
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="ban_user",
            details={
                "affected_users": affected_users
            },
            status="success",
            resource_type="users",
            resource_id=user_id if user_id else affected_users[0]["user_id"] if affected_users else None
        )
        
        # 返回成功响应
        return jsonify(
            code=0,
            message="禁用用户成功",
            data={
                "affected_users": affected_count
            }
        ), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 禁用用户异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="ban_user",
            details={
                "user_id": user_id,
                "user_name": user_name,
                "phonenumber": phonenumber,
                "error": str(e)
            },
            status="failed",
            resource_type="users",
            resource_id=user_id if user_id else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/unbanuser', methods=['POST'])
@admin_required
def unban_user(admin_id, admin_level):
    """
    解除用户禁用接口
    请求示例：/api/v1/admin/unbanuser?user_id=123&user_name=张三&phonenumber=13800138000
    
    参数说明（至少需要提供一个参数）：
    - user_id: 用户ID
    - user_name: 用户名
    - phonenumber: 手机号
    
    返回格式：
    {
        "code": 0,
        "message": "解除用户禁用成功",
        "data": {
            "affected_users": 被解除禁用的用户数量
        }
    }
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        user_name = request.args.get('user_name')
        phonenumber = request.args.get('phonenumber')
        
        # 验证至少提供了一个查询参数
        if not any([user_id, user_name, phonenumber]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="unban_user",
                details={"error": "未提供查询参数"},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="请至少提供一个查询参数：用户ID、用户名或手机号"
            ), 400
        
        # 构建查询条件
        query = User.query
        if user_id:
            query = query.filter(User.user_id == user_id)
        if user_name:
            query = query.filter(User.user_name == user_name)
        if phonenumber:
            query = query.filter(User.phonenumber == phonenumber)
        
        # 查询符合条件的用户
        users = query.all()
        
        # 检查是否找到用户
        if not users:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="unban_user",
                details={
                    "user_id": user_id,
                    "user_name": user_name,
                    "phonenumber": phonenumber,
                    "error": "未找到符合条件的用户"
                },
                status="failed",
                resource_type="users",
                resource_id=user_id if user_id else None
            )
            return jsonify(
                code=40400,
                message="未找到符合条件的用户"
            ), 404
        
        # 解除用户禁用
        affected_count = 0
        affected_users = []
        for user in users:
            user.is_active = True
            affected_count += 1
            affected_users.append({
                "user_id": user.user_id,
                "user_name": user.user_name,
                "phonenumber": user.phonenumber
            })
        
        # 提交数据库更改
        db.session.commit()
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="unban_user",
            details={
                "affected_users": affected_users
            },
            status="success",
            resource_type="users",
            resource_id=user_id if user_id else affected_users[0]["user_id"] if affected_users else None
        )
        
        # 返回成功响应
        return jsonify(
            code=0,
            message="解除用户禁用成功",
            data={
                "affected_users": affected_count
            }
        ), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 解除用户禁用异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="unban_user",
            details={
                "user_id": user_id,
                "user_name": user_name,
                "phonenumber": phonenumber,
                "error": str(e)
            },
            status="failed",
            resource_type="users",
            resource_id=user_id if user_id else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/deleteuser', methods=['DELETE'])
@admin_required
def delete_user(admin_id, admin_level):
    """
    删除用户接口
    请求示例：/api/v1/admin/deleteuser?user_id=123&user_name=张三&phonenumber=13800138000
    
    参数说明（至少需要提供一个参数）：
    - user_id: 用户ID
    - user_name: 用户名
    - phonenumber: 手机号
    
    返回格式：
    {
        "code": 0,
        "message": "删除用户成功",
        "data": {
            "affected_users": 被删除的用户数量,
            "deleted_users": [被删除的用户列表]
        }
    }
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        user_name = request.args.get('user_name')
        phonenumber = request.args.get('phonenumber')
        
        # 验证至少提供了一个查询参数
        if not any([user_id, user_name, phonenumber]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_user",
                details={"error": "未提供查询参数"},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="请至少提供一个查询参数：用户ID、用户名或手机号"
            ), 400
        
        # 构建查询条件
        query = User.query
        if user_id:
            query = query.filter(User.user_id == user_id)
        if user_name:
            query = query.filter(User.user_name == user_name)
        if phonenumber:
            query = query.filter(User.phonenumber == phonenumber)
        
        # 查询符合条件的用户
        users = query.all()
        
        # 检查是否找到用户
        if not users:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_user",
                details={
                    "user_id": user_id,
                    "user_name": user_name,
                    "phonenumber": phonenumber,
                    "error": "未找到符合条件的用户"
                },
                status="failed",
                resource_type="users",
                resource_id=user_id if user_id else None
            )
            return jsonify(
                code=40400,
                message="未找到符合条件的用户"
            ), 404
        
        # 记录要删除的用户信息
        deleted_users = []
        for user in users:
            deleted_users.append({
                "user_id": user.user_id,
                "user_name": user.user_name,
                "phonenumber": user.phonenumber
            })
        
        # 删除用户
        affected_count = 0
        for user in users:
            # 解除用户与设备的绑定关系
            for device in user.devices:
                device.user_id = None
            
            # 删除用户
            db.session.delete(user)
            affected_count += 1
        
        # 提交数据库更改
        db.session.commit()
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_user",
            details={
                "affected_users": affected_count,
                "deleted_users": deleted_users
            },
            status="success",
            resource_type="users",
            resource_id=user_id if user_id else deleted_users[0]["user_id"] if deleted_users else None
        )
        
        # 返回成功响应
        return jsonify(
            code=0,
            message="删除用户成功",
            data={
                "affected_users": affected_count,
                "deleted_users": deleted_users
            }
        ), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 删除用户异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_user",
            details={
                "user_id": user_id,
                "user_name": user_name,
                "phonenumber": phonenumber,
                "error": str(e)
            },
            status="failed",
            resource_type="users",
            resource_id=user_id if user_id else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/deletedevices', methods=['DELETE'])
@admin_required
def delete_device(admin_id, admin_level):
    """
    删除设备接口
    请求示例：/api/v1/admin/deletedevices?device_id=CQUCHX0503001
    
    参数说明：
    - device_id: 设备ID (必填)
    
    返回格式：
    {
        "code": 0,
        "message": "删除设备成功",
        "data": {
            "device_id": "被删除的设备ID"
        }
    }
    """
    try:
        # 获取查询参数
        device_id = request.args.get('device_id')
        
        # 验证是否提供了设备ID
        if not device_id:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_device",
                details={"error": "未提供设备ID"},
                status="failed",
                resource_type="devices",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="请提供设备ID"
            ), 400
        
        # 查询设备
        device = Device.query.get(device_id)
        
        # 检查是否找到设备
        if not device:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_device",
                details={
                    "device_id": device_id,
                    "error": "未找到指定设备"
                },
                status="failed",
                resource_type="devices",
                resource_id=device_id
            )
            return jsonify(
                code=40400,
                message="未找到指定设备"
            ), 404
        
        # 记录要删除的设备信息
        device_info = {
            "device_id": device.device_id,
            "user_id": device.user_id,
            "create_at": device.create_at.strftime("%Y-%m-%d %H:%M:%S") if device.create_at else None
        }
        
        # 删除设备
        db.session.delete(device)
        
        # 提交数据库更改
        db.session.commit()
        
        # 记录删除日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["device_bind_logs"]) as collection:
            collection.insert_one({
                "device_id": device_id,
                "user_id": device.user_id,
                "operation": "delete_device",
                "timestamp": datetime.now()
            })
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_device",
            details=device_info,
            status="success",
            resource_type="devices",
            resource_id=device_id
        )
        
        # 返回成功响应
        return jsonify(
            code=0,
            message="删除设备成功",
            data={
                "device_id": device_id
            }
        ), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 删除设备异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_device",
            details={
                "device_id": device_id,
                "error": str(e)
            },
            status="failed",
            resource_type="devices",
            resource_id=device_id
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/adduser', methods=['POST'])
@admin_required
def add_user(admin_id, admin_level):
    """
    管理员添加用户账号接口
    请求示例：
    {
        "username": "test",
        "password": "123456",
        "phonenumber": 12345678910,
        "is_admin": false,        # 可选，是否创建管理员账号
        "admin_level": 2          # 可选，管理员权限级别（1-3，1为超级管理员）
    }
    
    返回格式：
    {
        "code": 0,
        "message": "添加用户成功",
        "data": {
            "user_id": 新用户ID,
            "user_name": "用户名"
        }
    }
    
    或管理员账号：
    {
        "code": 0,
        "message": "添加管理员成功",
        "data": {
            "admin_id": 新管理员ID,
            "admin_name": "管理员名称",
            "admin_level": 管理员级别
        }
    }
    """
    try:
        # 1. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="add_user",
                details={"error": "无效的JSON格式"},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify({
                "code": Config.ERROR_CODES['INVALID_JSON'][0],
                "message": Config.ERROR_CODES['INVALID_JSON'][1]
            }), 400

        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        phonenumber = data.get('phonenumber')  # 获取手机号字段
        
        # 获取管理员相关字段
        is_admin = data.get('is_admin', False)
        new_admin_level = data.get('admin_level', 2)  # 默认为2级管理员
        
        # 验证必填字段
        if not username or not password:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="add_user",
                details={"error": "缺少必填字段"},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            return jsonify({
                "code": Config.ERROR_CODES['MISSING_FIELD'][0],
                "message": f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: username/password"
            }), 400
        
        # 如果是创建管理员账号，检查当前管理员权限
        if is_admin:
            # 只有超级管理员(level=1)可以创建管理员账号
            if admin_level != 1:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_admin_user",
                    details={"error": "权限不足，只有超级管理员可以创建管理员账号"},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify({
                    "code": 403,
                    "message": "权限不足，只有超级管理员可以创建管理员账号"
                }), 403
            
            # 验证管理员权限级别
            if not isinstance(new_admin_level, int) or new_admin_level < 1 or new_admin_level > 3:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_admin_user",
                    details={"error": "管理员权限级别无效", "admin_level": new_admin_level},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify({
                    "code": 40011,
                    "message": "管理员权限级别必须为1-3的整数（1最高，3最低）"
                }), 400
            
            # 检查管理员名是否已存在
            if Admin.query.filter_by(admin_name=username).first():
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_admin_user",
                    details={"error": "管理员名已存在", "admin_name": username},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify({
                    "code": 409,
                    "message": "管理员名已存在"
                }), 409
            
            # 创建管理员账号
            try:
                # 哈希密码
                hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
                new_admin = Admin(
                    admin_name=username,
                    admin_key=hashed_password.decode('utf-8'),
                    admin_level=new_admin_level,
                    create_at=datetime.now()
                )
                
                db.session.add(new_admin)
                db.session.commit()
                
                # 记录操作成功
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_admin_user",
                    details={
                        "new_admin_id": new_admin.admin_id,
                        "new_admin_name": username,
                        "new_admin_level": new_admin_level
                    },
                    status="success",
                    resource_type="admins",
                    resource_id=new_admin.admin_id
                )
                
                # 记录详细日志到MongoDB
                with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                    collection.insert_one({
                        "admin_id": new_admin.admin_id,
                        "admin_name": username,
                        "operation": "register",
                        "timestamp": datetime.now(),
                        "ip": get_client_ip(),
                        "status": "success",
                        "details": {
                            "created_by": admin_id,
                            "created_by_admin_level": admin_level
                        }
                    })
                
                return jsonify({
                    "code": 0,
                    "message": "添加管理员成功",
                    "data": {
                        "admin_id": new_admin.admin_id,
                        "admin_name": new_admin.admin_name,
                        "admin_level": new_admin.admin_level
                    }
                }), 201
                
            except Exception as e:
                db.session.rollback()
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_admin_user",
                    details={"error": str(e)},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                raise
            
        # 以下是原有的添加普通用户逻辑
        # 修复手机号验证逻辑
        if phonenumber is not None:
            # 确保手机号是字符串类型
            phonenumber = str(phonenumber)
            if not (phonenumber.isdigit() and len(phonenumber) == 11):
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_user",
                    details={"error": "手机号格式不正确", "phonenumber": phonenumber},
                    status="failed",
                    resource_type="users",
                    resource_id=None
                )
                return jsonify({
                    "code": 40013,
                    "message": "手机号格式不正确"
                }), 400

        # 2. 哈希密码
        password_bytes = password.encode('utf-8')
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')

        # 3. 使用ORM创建用户
        try:
            # 检查用户名是否已存在
            existing_user = User.query.filter_by(user_name=username).first()
            if existing_user:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="add_user",
                    details={"error": "用户名已存在", "username": username},
                    status="failed",
                    resource_type="users",
                    resource_id=None
                )
                return jsonify(
                    code=Config.ERROR_CODES['DUPLICATE_USER'][0],
                    message=Config.ERROR_CODES['DUPLICATE_USER'][1]
                ), 400
            
            # 创建新用户，添加手机号字段
            new_user = User(
                user_name=username,
                user_key=hashed_password,
                phonenumber=phonenumber,  # 添加手机号
                register_at=datetime.now()
            )
            
            db.session.add(new_user)
            db.session.commit()
            
            # 记录注册日志到MongoDB
            with mongo_collection(Config.MONGODB_COLLECTIONS["user_logs"]) as collection:
                collection.insert_one({
                    "user_id": new_user.user_id,
                    "username": username,
                    "phonenumber": phonenumber,  # 添加手机号到日志
                    "operation": "admin_add_user",  # 标记为管理员添加
                    "admin_id": admin_id,  # 添加管理员ID
                    "timestamp": datetime.now()
                })
            
            # 记录操作成功
            log_admin_operation(
                admin_id=admin_id,
                operation="add_user",
                details={
                    "user_id": new_user.user_id,
                    "username": username,
                    "phonenumber": phonenumber
                },
                status="success",
                resource_type="users",
                resource_id=new_user.user_id
            )
            
            return jsonify({
                "code": 0,
                "message": "添加用户成功",
                "data": {
                    "user_id": new_user.user_id,
                    "user_name": new_user.user_name
                }
            }), 200
            
        except Exception as e:
            db.session.rollback()
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="add_user",
                details={"error": str(e)},
                status="failed",
                resource_type="users",
                resource_id=None
            )
            raise

    except pymysql.IntegrityError:
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="add_user",
            details={"error": "用户名已存在"},
            status="failed",
            resource_type="users",
            resource_id=None
        )
        return jsonify(
            code=Config.ERROR_CODES['DUPLICATE_USER'][0],
            message=Config.ERROR_CODES['DUPLICATE_USER'][1]
        ), 400
    except Exception as e:
        import traceback
        traceback.print_exc()  # 打印完整堆栈跟踪
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="add_user",
            details={"error": str(e)},
            status="failed",
            resource_type="users",
            resource_id=None
        )
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@admin_bp.route('/v1/admin/adddevices', methods=['POST'])
@admin_required
def add_device(admin_id, admin_level):
    """
    添加设备接口
    请求示例：/api/v1/admin/adddevices?device_id=CQUCHX0503001&device_secret=your_secret_here
    
    参数说明：
    - device_id: 设备ID (必填)
    - device_secret: 设备密钥 (必填，将存储到device_key字段)
    
    返回格式：
    {
        "code": 0,
        "message": "添加设备成功",
        "data": {
            "device_id": "添加的设备ID"
        }
    }
    """
    try:
        # 从query参数获取
        device_id = request.args.get('device_id')
        device_secret = request.args.get('device_secret')
        
        # 校验参数
        if not device_id or not device_secret:
            log_admin_operation(
                admin_id=admin_id,
                operation="add_device",
                details={"error": "缺少device_id或device_secret"},
                status="failed",
                resource_type="devices",
                resource_id=None
            )
            return jsonify(
                code=40013,
                message="请提供device_id和device_secret"
            ), 400
        
        # 检查设备ID是否已存在
        existing_device = Device.query.get(device_id)
        if existing_device:
            log_admin_operation(
                admin_id=admin_id,
                operation="add_device",
                details={
                    "device_id": device_id,
                    "error": "设备ID已存在"
                },
                status="failed",
                resource_type="devices",
                resource_id=device_id
            )
            return jsonify(
                code=40011,
                message="设备ID已存在"
            ), 400
        
        # 创建新设备，存储device_secret到device_key
        new_device = Device(
            device_id=device_id,
            device_key=device_secret,
            create_at=datetime.now()
        )
        
        db.session.add(new_device)
        db.session.commit()
        
        # 记录添加日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["device_bind_logs"]) as collection:
            collection.insert_one({
                "device_id": device_id,
                "operation": "add_device",
                "timestamp": datetime.now()
            })
        
        log_admin_operation(
            admin_id=admin_id,
            operation="add_device",
            details={
                "device_id": device_id,
                "create_at": new_device.create_at.strftime("%Y-%m-%d %H:%M:%S") if new_device.create_at else None
            },
            status="success",
            resource_type="devices",
            resource_id=device_id
        )
        
        return jsonify(
            code=0,
            message="添加设备成功",
            data={
                "device_id": device_id
            }
        ), 200
        
    except Exception as e:
        db.session.rollback()
        print(f"[SYSTEM ERROR] 添加设备异常: {str(e)}")
        import traceback
        traceback.print_exc()
        log_admin_operation(
            admin_id=admin_id,
            operation="add_device",
            details={
                "device_id": device_id if 'device_id' in locals() else None,
                "error": str(e)
            },
            status="failed",
            resource_type="devices",
            resource_id=device_id if 'device_id' in locals() else None
        )
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/userdetail', methods=['GET'])
@admin_required
def get_user_detail(admin_id, admin_level):
    """
    获取用户详细信息接口，包括基本信息、关联设备和听歌记录
    请求示例：/api/v1/admin/userdetail?user_id=xxx&user_name=xxx&phonenumber=xxx
    
    参数说明（至少需要提供一个参数）：
    - user_id: 用户ID
    - user_name: 用户名
    - phonenumber: 手机号
    
    返回格式：
    {
        "code": 0,
        "message": "获取用户详情成功",
        "data": {
            "user_id": ...,
            "user_name": ...,
            "phonenumber": ...,
            "register_at": ...,
            "devices": [关联设备列表],
            "play_history": [听歌记录列表]
        }
    }
    """
    try:
        user_id = request.args.get('user_id')
        user_name = request.args.get('user_name')
        phonenumber = request.args.get('phonenumber')

        # 验证至少提供了一个查询参数
        if not any([user_id, user_name, phonenumber]):
            return jsonify(
                code=40010,
                message="请至少提供一个查询参数：用户ID、用户名或手机号"
            ), 400

        # 构建查询条件
        query = User.query
        if user_id:
            query = query.filter(User.user_id == user_id)
        if user_name:
            query = query.filter(User.user_name == user_name)
        if phonenumber:
            query = query.filter(User.phonenumber == phonenumber)

        user = query.first()
        if not user:
            return jsonify(
                code=40400,
                message="未找到符合条件的用户"
            ), 404

        # 获取用户基本信息
        user_data = {
            "user_id": user.user_id,
            "user_name": user.user_name,
            "phonenumber": user.phonenumber,
            "register_at": user.register_at.strftime("%Y-%m-%d %H:%M:%S") if user.register_at else None,
            "is_active": user.is_active
        }
        
        # 获取用户关联的设备列表
        devices = []
        try:
            # 使用显式列选择而不是全部字段，避免ORM自动查询不存在的字段
            user_devices = db.session.query(
                Device.device_id,
                Device.device_key,
                Device.user_id,
                Device.create_at
            ).filter(Device.user_id == user.user_id).all()
            
            print(f"[INFO] 找到用户 {user.user_id} 关联的设备数量: {len(user_devices)}")
            
            for device in user_devices:
                # 获取设备状态
                device_status = None
                try:
                    with mongo_collection(Config.MONGODB_COLLECTIONS.get("device_status", "device_status")) as collection:
                        status = collection.find_one(
                            {"device_id": device.device_id},
                            sort=[("timestamp", -1)]
                        )
                        if status:
                            device_status = {
                                "power": status.get("power", {}),
                                "network": status.get("network", {}),
                                "audio": status.get("audio", {})
                            }
                except Exception as e:
                    print(f"[WARNING] 获取设备状态异常: {str(e)}, 设备ID: {device.device_id}")
                    device_status = {"error": "无法获取设备状态"}
                
                device_data = {
                    "device_id": device.device_id,
                    "device_key": device.device_key,
                    "create_at": device.create_at.strftime("%Y-%m-%d %H:%M:%S") if device.create_at else None,
                    "status": device_status
                }
                devices.append(device_data)
        except Exception as e:
            print(f"[WARNING] 获取用户设备列表异常: {str(e)}, 用户ID: {user.user_id}")
            import traceback
            traceback.print_exc()
            devices = [{"error": f"获取设备列表异常: {str(e)}"}]
        
        # 获取用户的听歌记录
        play_history = []
        try:
            # 确保user_id是字符串格式 - MongoDB通常使用字符串ID
            user_id_str = str(user.user_id)
            print(f"[INFO] 正在查询用户 {user_id_str} 的听歌记录")
            
            with mongo_collection(Config.MONGODB_COLLECTIONS.get("play_history", "play_history")) as collection:
                # 查询用户最近的听歌记录，限制最多返回30条
                history_records = collection.find(
                    {"user_id": user_id_str},
                    sort=[("timestamp", -1)],
                    limit=30
                )
                
                # 转换为列表，避免游标失效
                history_list = list(history_records)
                print(f"[INFO] 找到用户听歌记录数量: {len(history_list)}")
                
                for record in history_list:
                    # 安全处理日期时间字段
                    played_at = None
                    if "timestamp" in record:
                        timestamp = record["timestamp"]
                        if hasattr(timestamp, "strftime"):
                            played_at = timestamp.strftime("%Y-%m-%d %H:%M:%S")
                        else:
                            # 可能是ISO字符串或其他格式
                            played_at = str(timestamp)
                    
                    history_item = {
                        "song_id": record.get("song_id"),
                        "song_name": record.get("song_name"),
                        "artist": record.get("artist"),
                        "album": record.get("album"),
                        "duration": record.get("duration"),
                        "played_at": played_at,
                        "device_id": record.get("device_id"),
                        "play_duration": record.get("play_duration")  # 实际播放时长
                    }
                    play_history.append(history_item)
        except Exception as e:
            print(f"[WARNING] 获取用户听歌记录异常: {str(e)}, 用户ID: {user.user_id}")
            import traceback
            traceback.print_exc()
            play_history = [{"error": f"获取听歌记录异常: {str(e)}"}]
        
        # 添加设备和听歌记录到返回数据
        user_data["devices"] = devices
        user_data["play_history"] = play_history
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query_user_detail",
            details={
                "user_id": user.user_id,
                "user_name": user.user_name,
                "phonenumber": user.phonenumber
            },
            status="success",
            resource_type="users",
            resource_id=user.user_id
        )
        
        return jsonify(
            code=0,
            message="获取用户详情成功",
            data=user_data
        ), 200
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户详情异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_user_detail",
            details={"error": str(e)},
            status="failed",
            resource_type="users",
            resource_id=user_id if 'user_id' in locals() else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500


@admin_bp.route('/v1/admin/login', methods=['POST'])
def admin_login():
    """
    管理员登录接口
    请求示例：
    {
        "admin_name": "admin",
        "admin_password": "password123"
    }
    
    返回格式：
    {
        "code": 0,
        "message": "登录成功",
        "data": {
            "admin_id": 1,
            "admin_name": "admin",
            "admin_level": 1,
            "expires_at": "2024-05-20T16:46:36Z"
        }
    }
    """
    try:
        # 1. 获取并校验请求数据
        if not request.is_json:
            # 记录登录失败
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "operation": "login_failed",
                    "reason": "invalid_json",
                    "timestamp": datetime.now(),
                    "ip": request.remote_addr
                })
            
            return jsonify({
                "code": Config.ERROR_CODES['INVALID_JSON'][0],
                "message": Config.ERROR_CODES['INVALID_JSON'][1]
            }), 400

        data = request.get_json()
        admin_name = data.get('admin_name')
        admin_key = data.get('admin_key')
        
        if not admin_name or not admin_key:
            # 记录登录失败
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "admin_name": admin_name if admin_name else "missing",
                    "operation": "login_failed",
                    "reason": "missing_fields",
                    "missing": "admin_name" if not admin_name else "admin_key" if not admin_key else "both",
                    "timestamp": datetime.now(),
                    "ip": request.remote_addr,
                    "status": "failed",
                    "details": {"missing_fields": "admin_name/admin_key"}
                })
                
            return jsonify({
                "code": Config.ERROR_CODES['MISSING_FIELD'][0],
                "message": f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: admin_name/admin_key"
            }), 400

        # 2. 查询管理员
        admin = Admin.query.filter_by(admin_name=admin_name).first()
        
        if not admin:
            # 记录登录失败
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "admin_name": admin_name,
                    "operation": "login_failed",
                    "reason": "admin_not_found",
                    "timestamp": datetime.now(),
                    "ip": get_client_ip(),
                    "status": "failed",
                    "details": {"error": "管理员不存在"}
                })
                
            return jsonify({
                "code": Config.ERROR_CODES['AUTH_FAILED'][0],
                "message": "管理员不存在或密码错误"
            }), 401

        # 3. 验证密码
        admin_input_password = admin_key.encode('utf-8')
        stored_password = admin.admin_key.encode('utf-8')
        
        if not bcrypt.checkpw(admin_input_password, stored_password):
            # 记录登录失败
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "admin_id": admin.admin_id,
                    "admin_name": admin_name,
                    "operation": "login_failed",
                    "reason": "password_incorrect",
                    "timestamp": datetime.now(),
                    "ip": get_client_ip(),
                    "status": "failed",
                    "details": {"error": "密码不正确"}
                })
                
            return jsonify({
                "code": Config.ERROR_CODES['AUTH_FAILED'][0],
                "message": "管理员不存在或密码错误"
            }), 401
            
        # 检查账号是否被禁用
        if not admin.is_active:
            # 记录登录失败
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "admin_id": admin.admin_id,
                    "admin_name": admin_name,
                    "operation": "login_failed",
                    "reason": "account_banned",
                    "timestamp": datetime.now(),
                    "ip": get_client_ip(),
                    "status": "failed",
                    "details": {"error": "账号已被禁用"}
                })
                
            return jsonify({
                "code": 40300,
                "message": "账号已被禁用，请联系超级管理员"
            }), 403

        # 4. 更新最后登录时间
        admin.last_login = datetime.now()
        db.session.commit()
        
        # 6. 记录登录日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin.admin_id,
                "admin_name": admin_name,
                "operation": "login",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "user_agent": request.user_agent.string if request.user_agent else None
            })

        # 8. 设置Cookie，方便客户端保存和使用令牌 - 确保跨域访问
        response = jsonify({
            "code": 0,
            "message": "登录成功",
            "data": {
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name,
                "admin_level": admin.admin_level
            }
        })
        
        # 提供更明确的使用指南
        response_data = {
            "code": 0,
            "message": "登录成功",
            "data": {
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name,
                "admin_level": admin.admin_level
            }
        }
        response.data = json.dumps(response_data).encode('utf-8')
        
        return response, 200

    except Exception as e:
        print(f"[SYSTEM ERROR] 管理员登录异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录登录失败日志
        try:
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
                collection.insert_one({
                    "admin_name": admin_name if 'admin_name' in locals() else "unknown",
                    "operation": "login_failed",
                    "timestamp": datetime.now(),
                    "ip": get_client_ip(),
                    "status": "failed",
                    "details": {"error": str(e)}
                })
        except Exception as log_error:
            print(f"[ERROR] 无法记录登录失败日志: {str(log_error)}")
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/register', methods=['POST'])
@admin_required
def admin_register(admin_id, admin_level):
    """
    注册新管理员接口
    请求示例：
    {
        "admin_name": "newadmin",  # 新管理员用户名
        "admin_password": "password123",  # 新管理员密码
        "admin_level": 1,  # 新管理员权限级别 (0为超级管理员，1为高级管理员，2为普通管理员，3为初级管理员)
        "current_admin_password": "yourpassword"  // 使用当前管理员的密码验证
    }
    
    返回格式：
    {
        "code": 0,
        "data": {
            "admin_id": 8,
            "admin_name": "fourzkw",
            "created_by": "dxj"
        },
        "message": "注册成功"
    }
    """
    try:
        # 0. 获取并校验请求数据
        if not request.is_json:
            return jsonify({
                "code": Config.ERROR_CODES['INVALID_JSON'][0],
                "message": Config.ERROR_CODES['INVALID_JSON'][1]
            }), 400

        data = request.get_json()
        
        # 获取新管理员信息
        admin_name = data.get('admin_name')
        admin_password = data.get('admin_password')
        new_admin_level = data.get('admin_level')
        
        # 获取当前管理员密码
        current_admin_password = data.get('current_admin_password')
        
        # 验证基本字段
        if not all([admin_name, admin_password, current_admin_password]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="register_admin",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 400, "message": "缺少必要字段"}), 400
        
        # 验证管理员权限级别
        if not isinstance(new_admin_level, int) or new_admin_level < 0 or new_admin_level > 3:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="register_admin",
                details={"error": "管理员权限级别无效", "admin_level": new_admin_level},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40011,
                "message": "管理员权限级别必须为0-3的整数（0为超级管理员，1为高级管理员，2为普通管理员，3为初级管理员）"
            }), 400

        # 1. 系统初始化和权限验证
        admin_count = Admin.query.count()
        
        # 如果系统中没有管理员，允许创建第一个管理员账号
        if admin_count == 0:
            print("[DEBUG] 系统中还没有管理员，允许创建第一个管理员账号")
            admin_creator_id = "first_admin"
            admin_creator_name = "system_init"
        else:
            # 获取当前管理员
            current_admin = Admin.query.get(admin_id)
            if not current_admin:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="register_admin",
                    details={"error": "当前操作的管理员不存在"},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify({"code": 404, "message": "当前操作的管理员不存在"}), 404
            
            # 检查是否尝试创建0级管理员
            if new_admin_level == 0:
                # 检查是否已存在0级管理员
                level_0_admin_exists = Admin.query.filter_by(admin_level=0).first() is not None
                if level_0_admin_exists:
                    # 记录操作失败
                    log_admin_operation(
                        admin_id=admin_id,
                        operation="register_admin",
                        details={"error": "已存在0级管理员，不能创建新的0级管理员"},
                        status="failed",
                        resource_type="admins",
                        resource_id=None
                    )
                    return jsonify({"code": 403, "message": "已存在0级管理员，不能创建新的0级管理员"}), 403
                else:
                    # 当不存在0级管理员时，允许创建0级管理员，无需验证创建者的级别
                    print("[DEBUG] 系统中不存在0级管理员，允许创建0级管理员")
                    # 继续处理，跳过后续权限检查
                    pass
            else:
                # 非0级管理员的创建需要进行权限检查
                
                # 检查权限级别
                if current_admin.admin_level > 0 and new_admin_level <= current_admin.admin_level:
                    # 记录操作失败
                    log_admin_operation(
                        admin_id=admin_id,
                        operation="register_admin",
                        details={"error": "权限不足，不能创建同级或更高级别的管理员", "current_level": current_admin.admin_level, "requested_level": new_admin_level},
                        status="failed",
                        resource_type="admins",
                        resource_id=None
                    )
                    return jsonify({"code": 403, "message": "权限不足，不能创建同级或更高级别的管理员"}), 403
                
                # 特殊规则：只有0级管理员可以创建1级管理员
                if new_admin_level == 1 and current_admin.admin_level != 0:
                    # 记录操作失败
                    log_admin_operation(
                        admin_id=admin_id,
                        operation="register_admin",
                        details={"error": "权限不足，只有0级管理员可以创建1级管理员", "current_level": current_admin.admin_level},
                        status="failed",
                        resource_type="admins",
                        resource_id=None
                    )
                    return jsonify({"code": 403, "message": "权限不足，只有0级管理员可以创建1级管理员"}), 403
            
            # 密码验证
            if not bcrypt.checkpw(current_admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="register_admin",
                    details={"error": "管理员密码验证失败"},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify({"code": 401, "message": "管理员密码验证失败"}), 401
            
            admin_creator_id = current_admin.admin_id
            admin_creator_name = current_admin.admin_name

        # 2. 检查新管理员名是否已存在
        if Admin.query.filter_by(admin_name=admin_name).first():
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="register_admin",
                details={"error": "管理员名已存在", "admin_name": admin_name},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 409, "message": "管理员名已存在"}), 409

        # 3. 创建新管理员
        hashed_password = bcrypt.hashpw(admin_password.encode('utf-8'), bcrypt.gensalt())
        new_admin = Admin(
            admin_name=admin_name,
            admin_key=hashed_password.decode('utf-8'),
            admin_level=new_admin_level,
            create_at=datetime.now()
        )
        
        db.session.add(new_admin)
        db.session.commit()
        
        # 4. 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="register_admin",
            details={
                "new_admin_id": new_admin.admin_id,
                "new_admin_name": admin_name,
                "new_admin_level": new_admin_level
            },
            status="success",
            resource_type="admins",
            resource_id=new_admin.admin_id
        )

        return jsonify({
            "code": 0,
            "message": "注册成功",
            "data": {
                "admin_id": new_admin.admin_id,
                "admin_name": new_admin.admin_name,
                "created_by": admin_creator_name
            }
        }), 201

    except Exception as e:
        db.session.rollback()
        print(f"[ERROR] 管理员注册失败: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="register_admin",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=None
        )
        
        # 返回更详细的错误信息（仅限开发环境）
        return jsonify({
            "code": 500,
            "message": "注册失败",
            "error": str(e)  # 生产环境应移除此字段
        }), 500

@admin_bp.route('/v1/admin/changepassword', methods=['POST'])
@admin_required
def change_admin_password(admin_id, admin_level):
    """
    修改管理员密码接口，仅1级管理员可以修改自己的密码
    请求示例：
    {
        "admin_name": "admin",  # 管理员用户名
        "current_password": "oldpassword",  # 当前密码
        "new_password": "newpassword123"  # 新密码
    }
    
    返回格式：
    {
        "code": 0,
        "data": {
            "admin_id": 1,
            "admin_name": "admin"
        },
        "message": "密码修改成功"
    }
    """
    try:
        # 1. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_password",
                details={"error": "请求格式错误，需要JSON格式"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 400, "message": "请求格式错误，需要JSON格式"}), 400

        data = request.get_json()
        
        # 获取管理员信息和密码
        admin_name = data.get('admin_name')
        current_password = data.get('current_password')
        new_password = data.get('new_password')
        
        # 验证基本字段
        if not all([admin_name, current_password, new_password]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_password",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 400, "message": "缺少必要字段"}), 400
        
        # 2. 验证管理员身份
        admin = Admin.query.filter_by(admin_name=admin_name).first()
        if not admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_password",
                details={"error": "管理员不存在", "admin_name": admin_name},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 404, "message": "管理员不存在"}), 404
        
        # 4. 验证当前密码
        if not bcrypt.checkpw(current_password.encode('utf-8'), admin.admin_key.encode('utf-8')):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_password",
                details={
                    "error": "当前密码验证失败",
                    "target_admin_id": admin.admin_id
                },
                status="failed",
                resource_type="admins",
                resource_id=admin.admin_id
            )
            return jsonify({"code": 401, "message": "当前密码验证失败"}), 401
        
        # 5. 修改密码
        hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
        admin.admin_key = hashed_password.decode('utf-8')
        
        # 6. 记录修改时间（如果字段存在）
        try:
            admin.update_at = datetime.now()
        except:
            pass
            
        db.session.commit()
        
        # 7. 记录操作日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name,
                "operation": "change_password",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "user_agent": request.user_agent.string if request.user_agent else None
            })
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="change_password",
            details={
                "target_admin_id": admin.admin_id,
                "target_admin_name": admin.admin_name
            },
            status="success",
            resource_type="admins",
            resource_id=admin.admin_id
        )

        return jsonify({
            "code": 0,
            "data": {
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name
            },
            "message": "密码修改成功"
        }), 200

    except Exception as e:
        db.session.rollback()
        print(f"[ERROR] 修改管理员密码失败: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="change_password",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=None
        )
        
        # 返回更详细的错误信息（仅限开发环境）
        return jsonify({
            "code": 500,
            "message": "修改密码失败",
            "error": str(e)  # 生产环境应移除此字段
        }), 500

@admin_bp.route('/v1/admin/reset_admin_password', methods=['POST'])
@admin_required
def reset_admin_password(admin_id, admin_level):
    """
    超级管理员（1级）重置其他管理员（0级）密码的接口
    请求示例：
    {
        "target_admin_id": 2,  # 目标管理员ID
        "new_password": "newpassword123",  # 新密码
        "current_admin_password": "yourpassword"  # 当前超级管理员的密码（验证身份）
    }
    
    返回格式：
    {
        "code": 0,
        "data": {
            "target_admin_id": 2,
            "target_admin_name": "admin2"
        },
        "message": "密码重置成功"
    }
    """
    try:
        # 1. 验证管理员权限（仅1级管理员可操作）
        if admin_level != 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={"error": "权限不足，只有1级管理员可以重置其他管理员密码"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40300,
                "message": "权限不足，只有1级管理员可以重置其他管理员密码"
            }), 403

        # 2. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={"error": "请求格式错误，需要JSON格式"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 40000, "message": "请求格式错误，需要JSON格式"}), 400

        data = request.get_json()
        
        # 获取参数
        target_admin_id = data.get('target_admin_id')
        new_password = data.get('new_password')
        current_admin_password = data.get('current_admin_password')
        
        # 验证基本字段
        if not all([target_admin_id, new_password, current_admin_password]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 40000, "message": "缺少必要字段"}), 400
        
        # 3. 验证当前管理员密码
        current_admin = Admin.query.filter_by(admin_id=admin_id).first()
        if not current_admin or not bcrypt.checkpw(current_admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={"error": "当前管理员密码验证失败"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({"code": 40100, "message": "当前管理员密码验证失败"}), 401
        
        # 4. 查找目标管理员
        target_admin = Admin.query.filter_by(admin_id=target_admin_id).first()
        if not target_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={"error": "目标管理员不存在", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({"code": 40400, "message": "目标管理员不存在"}), 404
        
        # 5. 验证目标管理员等级（只能修改0级管理员密码）
        if target_admin.admin_level != 0:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reset_admin_password",
                details={
                    "error": "只能修改0级管理员密码",
                    "target_admin_id": target_admin_id,
                    "target_admin_level": target_admin.admin_level
                },
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({"code": 40300, "message": "只能修改0级管理员密码"}), 403
        
        # 6. 修改密码
        hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
        target_admin.admin_key = hashed_password.decode('utf-8')
        
        # 7. 记录修改时间（如果字段存在）
        try:
            target_admin.update_at = datetime.now()
        except:
            pass
            
        db.session.commit()
        
        # 8. 记录操作日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin_id,
                "admin_name": current_admin.admin_name,
                "operation": "reset_admin_password",
                "target_admin_id": target_admin.admin_id,
                "target_admin_name": target_admin.admin_name,
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "user_agent": request.user_agent.string if request.user_agent else None
            })
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="reset_admin_password",
            details={
                "target_admin_id": target_admin.admin_id,
                "target_admin_name": target_admin.admin_name
            },
            status="success",
            resource_type="admins",
            resource_id=target_admin.admin_id
        )

        return jsonify({
            "code": 0,
            "data": {
                "target_admin_id": target_admin.admin_id,
                "target_admin_name": target_admin.admin_name
            },
            "message": "密码重置成功"
        }), 200

    except Exception as e:
        db.session.rollback()
        print(f"[ERROR] 重置管理员密码失败: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="reset_admin_password",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=None
        )
        
        # 返回更详细的错误信息（仅限开发环境）
        return jsonify({
            "code": 500,
            "message": "重置密码失败",
            "error": str(e)  # 生产环境应移除此字段
        }), 500

@admin_bp.route('/v1/admin/list', methods=['GET'])
@admin_required
def get_all_admins(admin_id, admin_level):
    """
    获取所有管理员信息的接口，支持分页
    请求示例：/api/v1/admin/list?size=10&page=1
    
    参数说明：
    - page: 页码，默认为1
    - size: 每页记录数，默认为10
    
    返回格式：
    {
        "code": 0,
        "message": "获取管理员列表成功",
        "data": {
            "total": 总管理员数,
            "page": 当前页码,
            "size": 每页记录数,
            "total_pages": 总页数,
            "admins": [管理员列表]
        }
    }
    """
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        
        # 验证分页参数
        if page < 1 or size < 1:
            return jsonify({
                "code": 40010,
                "message": "页码和每页数量必须为正整数"
            }), 400
        
        # 查询管理员总数
        total_admins = Admin.query.count()
        
        # 计算总页数
        total_pages = (total_admins + size - 1) // size if total_admins > 0 else 0
        
        # 查询管理员数据（按创建时间降序排列）
        admins = Admin.query.order_by(desc(Admin.create_at)).paginate(
            page=page, per_page=size, error_out=False
        )
        
        # 从 MongoDB 获取所有管理员的最后登录时间
        last_login_dict = {}
        try:
            with mongo_collection(Config.MONGODB_COLLECTIONS.get("admin_logs", "admin_logs")) as collection:
                # 获取所有管理员的最后登录记录
                pipeline = [
                    {"$match": {"operation": "login"}},
                    {"$sort": {"timestamp": -1}},
                    {"$group": {
                        "_id": "$admin_id",
                        "last_login_time": {"$first": "$timestamp"}
                    }}
                ]
                last_login_records = list(collection.aggregate(pipeline))
                
                # 构建管理员ID到最后登录时间的映射
                for record in last_login_records:
                    admin_id_key = record["_id"]
                    last_login_time = record["last_login_time"]
                    if isinstance(last_login_time, datetime):
                        last_login_dict[admin_id_key] = last_login_time.strftime("%Y-%m-%d %H:%M:%S")
                    else:
                        last_login_dict[admin_id_key] = last_login_time
        except Exception as mongo_error:
            print(f"[WARNING] MongoDB 查询最后登录时间失败: {str(mongo_error)}")
            # 如果 MongoDB 查询失败，仍然可以返回基本的管理员信息
        
        # 构建管理员列表
        admin_list = []
        for admin in admins.items:
            # 从 MongoDB 获取最后登录时间，如果没有则使用数据库中的 last_login 作为备选
            mongo_last_login = last_login_dict.get(admin.admin_id)
            db_last_login = admin.last_login.strftime("%Y-%m-%d %H:%M:%S") if admin.last_login else None
            
            admin_data = {
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name,
                "admin_level": admin.admin_level,
                "create_at": admin.create_at.strftime("%Y-%m-%d %H:%M:%S") if admin.create_at else None,
                "last_login": mongo_last_login if mongo_last_login else db_last_login,
                "is_active": admin.is_active
            }
            admin_list.append(admin_data)
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取管理员列表成功",
            "data": {
                "total": total_admins,
                "page": page,
                "size": size,
                "total_pages": total_pages,
                "admins": admin_list
            }
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query_admin_list",
            details={
                "page": page,
                "size": size,
                "total": total_admins
            },
            status="success",
            resource_type="admins",
            resource_id=None
        )
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取管理员列表异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_admin_list",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/log_activity', methods=['GET'])
@admin_required
def get_admin_activity_logs(admin_id, admin_level):
    """
    获取管理员活动日志接口
    请求示例：/api/v1/admin/log_activity?query_admin_id=1&page=1&page_size=20
    或者：/api/v1/admin/log_activity （返回所有管理员日志）
    
    参数说明：
    - query_admin_id: 要查询的管理员ID (可选，如果为空则返回所有管理员日志)
    - page: 页码，默认为1
    - page_size: 每页返回的日志数量，默认为50条，最大200条
    
    权限要求：
    - 只有1级管理员可以查询管理员的活动日志
    
    返回格式：
    {
        "code": 0,
        "message": "获取管理员活动日志成功",
        "data": {
            "admin_id": 查询的管理员ID（如果指定了的话）,
            "pagination": {
                "page": 当前页码,
                "page_size": 每页数量,
                "total_logs": 总日志数量,
                "total_pages": 总页数
            },
            "logs": [活动日志列表]
        }
    }
    """
    try:
        # 获取要查询的管理员ID（可选参数）
        query_admin_id = request.args.get('query_admin_id')
        
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        
        # 验证分页参数
        if page < 1:
            return jsonify({
                "code": 40010,
                "message": "页码必须大于0"
            }), 400
            
        if page_size < 1 or page_size > 200:
            return jsonify({
                "code": 40010,
                "message": "每页日志数量必须在1-200之间"
            }), 400
        
        # 检查权限 - 只有0,1级管理员可以查询
        if admin_level >= 2:
            # 记录未授权访问
            log_admin_operation(
                admin_id=admin_id,
                operation="query_admin_logs",
                details={
                    "query_admin_id": query_admin_id,
                    "error": "权限不足"
                },
                status="failed",
                resource_type="admin_logs"
            )
            return jsonify(
                code=40300,
                message="权限不足，只有1级管理员可以查询管理员活动日志"
            ), 403

        # 如果指定了query_admin_id，验证被查询的管理员是否存在
        target_admin = None
        if query_admin_id:
            target_admin = Admin.query.get(query_admin_id)
            if not target_admin:
                return jsonify(
                    code=40400,
                    message="要查询的管理员不存在"
                ), 404

        # 从MongoDB获取管理员活动日志
        logs = []
        total_logs = 0
        try:
            # 使用admin_logs集合查询管理员日志
            collection_name = Config.MONGODB_COLLECTIONS.get("admin_logs", "admin_logs")
            print(f"[INFO] 查询管理员日志，使用集合: {collection_name}")
            
            with mongo_collection(collection_name) as collection:
                # 构建查询条件
                if query_admin_id:
                    # 查询指定管理员的活动记录
                    query_filter = {"admin_id": int(query_admin_id)}
                else:
                    # 查询所有管理员的活动记录
                    query_filter = {}
                
                # 获取总记录数
                total_logs = collection.count_documents(query_filter)
                
                # 计算总页数
                total_pages = (total_logs + page_size - 1) // page_size if total_logs > 0 else 0
                
                # 计算跳过的文档数量
                skip = (page - 1) * page_size
                
                admin_logs = collection.find(
                    query_filter,
                    sort=[("timestamp", -1)],
                    skip=skip,
                    limit=page_size
                )
                
                # 转换为列表并格式化数据
                for log in admin_logs:
                    # 处理ObjectId，将其转为字符串
                    log["_id"] = str(log["_id"])
                    
                    # 格式化时间
                    if "timestamp" in log and isinstance(log["timestamp"], datetime):
                        log["timestamp"] = log["timestamp"].strftime("%Y-%m-%d %H:%M:%S")
                    
                    logs.append(log)

            # 记录操作成功
            log_admin_operation(
                admin_id=admin_id,
                operation="query_admin_logs",
                details={
                    "query_admin_id": query_admin_id,
                    "page": page,
                    "page_size": page_size,
                    "found_logs": len(logs),
                    "total_logs": total_logs
                },
                status="success",
                resource_type="admin_logs",
                resource_id=query_admin_id
            )

            # 构建响应数据
            response_data = {
                "pagination": {
                    "page": page,
                    "page_size": page_size,
                    "total_logs": total_logs,
                    "total_pages": total_pages
                },
                "logs": logs
            }
            
            # 如果查询特定管理员，添加管理员信息
            if query_admin_id and target_admin:
                response_data.update({
                    "admin_id": query_admin_id,
                    "admin_name": target_admin.admin_name,
                    "admin_level": target_admin.admin_level
                })

            response = {
                "code": 0,
                "message": "获取管理员活动日志成功",
                "data": response_data
            }

            return jsonify(response), 200
            
        except Exception as e:
            print(f"[ERROR] 查询MongoDB管理员日志异常: {str(e)}")
            import traceback
            traceback.print_exc()
            
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_admin_logs",
                details={
                    "query_admin_id": query_admin_id if 'query_admin_id' in locals() else None,
                    "page": page,
                    "page_size": page_size,
                    "error": str(e)
                },
                status="failed",
                resource_type="admin_logs"
            )
            
            return jsonify(
                code=50000,
                message="系统繁忙，请稍后重试",
                error=str(e)
            ), 500
        
    except Exception as e:
        # 记录错误日志
        print(f"[SYSTEM ERROR] 获取管理员活动日志异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_admin_logs",
            details={
                "query_admin_id": query_admin_id if 'query_admin_id' in locals() else None,
                "page": page if 'page' in locals() else None,
                "page_size": page_size if 'page_size' in locals() else None,
                "error": str(e)
            },
            status="failed",
            resource_type="admin_logs"
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@admin_bp.route('/v1/admin/user_activity', methods=['GET'])
@admin_required
def get_user_activity(admin_id, admin_level):
    """
    获取用户活跃度统计信息接口，基于用户播放音乐的次数
    请求示例：/api/v1/admin/user_activity?days=30
    
    参数说明：
    - days: 统计天数，默认为30天
    
    返回格式：
    {
        "code": 0,
        "message": "获取用户活跃度统计成功",
        "data": {
            "total_users": 用户总数,
            "active_users": 活跃用户数（有播放记录的用户）,
            "total_plays": 总播放次数,
            "daily_activity": [
                {
                    "date": "2024-05-01",
                    "active_users": 活跃用户数,
                    "play_count": 播放次数
                },
                ...
            ],
            "weekly_summary": [
                {
                    "week": "第1周 (2024-05-01 to 2024-05-07)",
                    "active_users": 活跃用户数,
                    "play_count": 播放次数
                },
                ...
            ],
            "monthly_summary": [
                {
                    "month": "2024-05",
                    "active_users": 活跃用户数,
                    "play_count": 播放次数
                },
                ...
            ],
            "user_stats": [
                {
                    "user_id": 用户ID,
                    "user_name": 用户名,
                    "play_count": 播放次数,
                    "last_played_at": 最后一次播放时间
                },
                ...
            ]
        }
    }
    """
    try:
        # 记录操作开始
        log_admin_operation(
            admin_id=admin_id,
            operation="query_user_activity",
            details={"action": "开始查询用户活跃度统计"},
            status="started",
            resource_type="statistics",
            resource_id=None
        )
        
        # 获取天数参数
        days = request.args.get('days', 30, type=int)
        
        # 验证参数
        if days < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_user_activity",
                details={"error": "统计天数必须为正整数", "days": days},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "统计天数必须为正整数"
            }), 400
        
        # 计算时间范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        print(f"[INFO] 统计时间范围: {start_date} 至 {end_date}")
        
        # 获取所有用户，预先加载用户信息
        all_users = User.query.all()
        # 创建两种映射：字符串ID到用户 和 整数ID到用户
        str_user_dict = {}
        int_user_dict = {}
        
        for user in all_users:
            str_id, int_id = normalize_user_id(user.user_id)
            if str_id:
                str_user_dict[str_id] = user
            if int_id is not None:
                int_user_dict[int_id] = user
                
        print(f"[INFO] 预加载系统用户总数: {len(all_users)}")
        print(f"[INFO] 字符串ID映射: {len(str_user_dict)}个, 整数ID映射: {len(int_user_dict)}个")
        
        # 输出几个用户ID用于调试
        sample_str_ids = list(str_user_dict.keys())[:3] if str_user_dict else []
        sample_int_ids = list(int_user_dict.keys())[:3] if int_user_dict else []
        print(f"[DEBUG] 字符串ID示例: {sample_str_ids}")
        print(f"[DEBUG] 整数ID示例: {sample_int_ids}")
        
        # 初始化统计数据
        user_stats = []
        total_plays = 0
        active_users_set = set()  # 存储标准化后的字符串ID
        
        # 初始化每日活跃数据
        daily_activity = {}
        daily_active_users = {}
        
        # 初始化日期范围内的所有日期
        current_date = start_date
        while current_date <= end_date:
            date_str = current_date.strftime("%Y-%m-%d")
            daily_activity[date_str] = 0  # 初始化播放次数为0
            daily_active_users[date_str] = set()  # 初始化活跃用户集合
            current_date += timedelta(days=1)
        
        # 从MongoDB获取播放记录
        try:
            # 首先尝试查询listen_records集合
            collection_name = Config.MONGODB_COLLECTIONS.get("listen_records", "listen_records")
            print(f"[INFO] 尝试查询MongoDB集合: {collection_name}")
            
            with mongo_collection(collection_name) as collection:
                # 尝试不同的查询方式 - 首先查询listen_records集合，与用户接口相同
                
                # 使用日期查询条件
                date_end = end_date.strftime("%Y-%m-%d")
                date_start = start_date.strftime("%Y-%m-%d")
                play_records = list(collection.find({
                    "date": {"$gte": date_start, "$lte": date_end}
                }))
                
                print(f"[INFO] 使用date字段查询到记录数量: {len(play_records)}")
                
                # 如果找不到记录，尝试使用timestamp字段
                if not play_records:
                    print(f"[INFO] 未找到记录，尝试使用timestamp字段查询")
                    
                    with mongo_collection(Config.MONGODB_COLLECTIONS.get("play_history", "play_history")) as history_collection:
                        play_records = list(history_collection.find({
                            "timestamp": {"$gte": start_date, "$lte": end_date}
                        }))
                        
                        print(f"[INFO] 使用timestamp字段查询到记录数量: {len(play_records)}")
                
                # 如果没有找到记录，直接返回空结果
                if not play_records:
                    print("[WARNING] 未找到播放记录，返回空统计结果")
                    # 构建空的每日活跃数据
                    empty_daily_activity = []
                    current_date = start_date
                    while current_date <= end_date:
                        date_str = current_date.strftime("%Y-%m-%d")
                        empty_daily_activity.append({
                            "date": date_str,
                            "active_users": 0,
                            "play_count": 0
                        })
                        current_date += timedelta(days=1)
                    
                    # 构建空的周汇总数据
                    empty_weekly_summary = []
                    # 构建空的月汇总数据
                    empty_monthly_summary = []
                    
                    return jsonify({
                        "code": 0,
                        "message": "获取用户活跃度统计成功，但没有找到播放记录",
                        "data": {
                            "total_users": len(all_users),
                            "active_users": 0,
                            "total_plays": 0,
                            "days": days,
                            "daily_activity": empty_daily_activity,
                            "weekly_summary": empty_weekly_summary,
                            "monthly_summary": empty_monthly_summary,
                            "user_stats": []
                        }
                    }), 200
                
                # 按用户ID分组并计数
                user_play_counts = {}  # 用户播放次数，键为标准化后的字符串ID
                user_last_played = {}  # 用户最后播放时间，键为标准化后的字符串ID
                
                # 先打印几条记录的详细信息用于调试
                sample_records = play_records[:3] if len(play_records) >= 3 else play_records
                for i, record in enumerate(sample_records):
                    print(f"[DEBUG] 示例记录{i+1}: {record}")
                    user_id = record.get("user_id")
                    # 如果没有user_id字段，尝试获取其他可能的字段
                    if user_id is None:
                        fields = list(record.keys())
                        print(f"[WARNING] 记录没有user_id字段，字段列表: {fields}")
                    song_name = record.get("song_name", "未知歌曲")
                    str_id, int_id = normalize_user_id(user_id)
                    print(f"[DEBUG] 示例记录{i+1}: 原始user_id={user_id}, 类型={type(user_id)}, 标准化后: str_id={str_id}, int_id={int_id}, 歌曲={song_name}")
                
                for record in play_records:
                    user_id = record.get("user_id")
                    
                    if not user_id:
                        print(f"[WARNING] 跳过无用户ID的播放记录: {record.get('song_name', '未知歌曲')}")
                        continue
                    
                    # 标准化用户ID
                    str_id, int_id = normalize_user_id(user_id)
                    if not str_id:
                        print(f"[WARNING] 无法标准化用户ID: {user_id}, 类型: {type(user_id)}")
                        continue
                    
                    total_plays += 1
                    active_users_set.add(str_id)
                    
                    # 获取记录的日期
                    record_date = None
                    timestamp = record.get("timestamp")
                    date_str = record.get("date")
                    
                    if timestamp and hasattr(timestamp, "strftime"):
                        record_date = timestamp.date()
                        date_str = record_date.strftime("%Y-%m-%d")
                    elif date_str:
                        try:
                            record_date = datetime.strptime(date_str, "%Y-%m-%d").date()
                        except (ValueError, TypeError):
                            print(f"[WARNING] 无法解析日期: {date_str}")
                            continue
                    else:
                        print(f"[WARNING] 记录缺少日期信息")
                        continue
                    
                    # 确保日期在查询范围内
                    if record_date < start_date.date() or record_date > end_date.date():
                        print(f"[WARNING] 日期 {date_str} 不在查询范围内")
                        continue
                        
                    # 更新每日活跃统计
                    if date_str in daily_activity:
                        daily_activity[date_str] += 1
                        daily_active_users[date_str].add(str_id)
                    
                    # 更新用户播放次数
                    if str_id in user_play_counts:
                        user_play_counts[str_id] += 1
                    else:
                        user_play_counts[str_id] = 1
                    
                    # 更新用户最后播放时间
                    if timestamp:
                        if str_id not in user_last_played or timestamp > user_last_played[str_id]:
                            user_last_played[str_id] = timestamp
        except Exception as e:
            print(f"[ERROR] 查询MongoDB播放记录异常: {str(e)}")
            import traceback
            traceback.print_exc()
            # 返回部分数据，而不是完全失败
            return jsonify({
                "code": 50001,
                "message": "获取播放记录异常，返回部分数据",
                "error": str(e),
                "data": {
                    "total_users": len(all_users),
                    "active_users": 0,
                    "total_plays": 0,
                    "days": days,
                    "daily_activity": [],
                    "weekly_summary": [],
                    "monthly_summary": [],
                    "user_stats": []
                }
            }), 500
        
        # 打印活跃用户信息
        print(f"[INFO] 活跃用户ID总数: {len(active_users_set)}, 总播放次数: {total_plays}")
        
        # 构建每日活跃数据列表
        daily_activity_list = []
        for date_str in sorted(daily_activity.keys()):
            daily_activity_list.append({
                "date": date_str,
                "active_users": len(daily_active_users[date_str]),
                "play_count": daily_activity[date_str]
            })
        
        # 构建周汇总数据
        weekly_summary = []
        # 按周分组
        current_week_start = start_date
        while current_week_start <= end_date:
            current_week_end = min(current_week_start + timedelta(days=6), end_date)
            week_str = f"第{(current_week_start - start_date).days // 7 + 1}周 ({current_week_start.strftime('%Y-%m-%d')} to {current_week_end.strftime('%Y-%m-%d')})"
            
            # 计算该周的活跃用户和播放次数
            week_play_count = 0
            week_active_users = set()
            
            current_date = current_week_start
            while current_date <= current_week_end:
                date_str = current_date.strftime("%Y-%m-%d")
                if date_str in daily_activity:
                    week_play_count += daily_activity[date_str]
                    week_active_users.update(daily_active_users[date_str])
                current_date += timedelta(days=1)
            
            weekly_summary.append({
                "week": week_str,
                "active_users": len(week_active_users),
                "play_count": week_play_count
            })
            
            current_week_start += timedelta(days=7)
        
        # 构建月汇总数据
        monthly_summary = []
        # 按月分组
        months = {}
        for date_str in daily_activity:
            month_str = date_str[:7]  # 取YYYY-MM部分
            if month_str not in months:
                months[month_str] = {
                    "play_count": 0,
                    "active_users": set()
                }
            months[month_str]["play_count"] += daily_activity[date_str]
            months[month_str]["active_users"].update(daily_active_users[date_str])
        
        for month_str in sorted(months.keys()):
            monthly_summary.append({
                "month": month_str,
                "active_users": len(months[month_str]["active_users"]),
                "play_count": months[month_str]["play_count"]
            })
        
        # 现在获取用户详细信息并构建统计列表
        matched_count = 0
        print(f"[INFO] 开始构建用户统计信息...")
        
        for str_id in active_users_set:
            try:
                # 尝试从预加载的字典中查找用户
                user = None
                play_count = user_play_counts.get(str_id, 0)
                last_played = user_last_played.get(str_id)
                last_played_str = last_played.strftime("%Y-%m-%d %H:%M:%S") if last_played else None
                
                # 先尝试从字符串ID映射中获取
                if str_id in str_user_dict:
                    user = str_user_dict[str_id]
                    matched_count += 1
                    print(f"[INFO] 通过字符串ID匹配到用户: {user.user_name}, ID: {user.user_id}")
                    
                # 如果找不到，尝试从整数ID映射中获取
                elif str_id.isdigit() and int(str_id) in int_user_dict:
                    user = int_user_dict[int(str_id)]
                    matched_count += 1
                    print(f"[INFO] 通过整数ID匹配到用户: {user.user_name}, ID: {user.user_id}")
                
                # 如果找到了用户，添加统计信息
                if user:
                    user_data = {
                        "user_id": user.user_id,
                        "user_name": user.user_name,
                        "play_count": play_count,
                        "last_played_at": last_played_str
                    }
                    user_stats.append(user_data)
                else:
                    # 用户不存在，但仍添加记录便于调试
                    print(f"[WARNING] 未找到用户ID: {str_id}")
                    user_stats.append({
                        "user_id": str_id,
                        "user_name": "未知用户",
                        "play_count": play_count,
                        "last_played_at": last_played_str,
                        "note": "系统中找不到此用户"
                    })
            except Exception as e:
                print(f"[ERROR] 处理用户 {str_id} 数据异常: {str(e)}")
                import traceback
                traceback.print_exc()
        
        # 按播放次数降序排序
        user_stats.sort(key=lambda x: x["play_count"], reverse=True)
        
        print(f"[INFO] 最终统计: 用户总数 {len(all_users)}, 活跃用户 {len(active_users_set)}, 匹配用户 {matched_count}, 总播放 {total_plays}, 统计用户 {len(user_stats)}")
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取用户活跃度统计成功",
            "data": {
                "total_users": len(all_users),
                "active_users": len(active_users_set),
                "total_plays": total_plays,
                "days": days,
                "daily_activity": daily_activity_list,
                "weekly_summary": weekly_summary,
                "monthly_summary": monthly_summary,
                "user_stats": user_stats
            }
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query_user_activity",
            details={
                "days": days,
                "total_users": len(all_users),
                "active_users": len(active_users_set),
                "total_plays": total_plays
            },
            status="success",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户活跃度统计异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_user_activity",
            details={"error": str(e)},
            status="failed",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/device_activity', methods=['GET'])
@admin_required
def get_device_activity(admin_id, admin_level):
    """
    获取设备活跃度统计信息接口，基于MongoDB中的设备状态集合
    请求示例：/api/v1/admin/device_activity?days=30
    
    参数说明：
    - days: 统计天数，默认为30天
    
    返回格式：
    {
        "code": 0,
        "message": "获取设备活跃度统计成功",
        "data": {
            "total_devices": 设备总数,
            "active_devices": 活跃设备数（有开机记录的设备）,
            "total_active_days": 总活跃天数（所有设备活跃天数之和）,
            "daily_activity": [
                {
                    "date": "2024-05-01",
                    "active_devices": 活跃设备数
                },
                ...
            ],
            "weekly_summary": [
                {
                    "week": "第1周 (2024-05-01 to 2024-05-07)",
                    "active_devices": 活跃设备数
                },
                ...
            ],
            "monthly_summary": [
                {
                    "month": "2024-05",
                    "active_devices": 活跃设备数
                },
                ...
            ],
            "device_stats": [
                {
                    "device_id": 设备ID,
                    "user_id": 绑定的用户ID,
                    "user_name": 绑定的用户名,
                    "active_days": 活跃天数,
                    "last_active": 最后一次活跃时间
                },
                ...
            ]
        }
    }
    """
    try:
        # 记录操作开始
        log_admin_operation(
            admin_id=admin_id,
            operation="query_device_activity",
            details={"action": "开始查询设备活跃度统计"},
            status="started",
            resource_type="statistics",
            resource_id=None
        )
        
        # 获取天数参数
        days = request.args.get('days', 30, type=int)
        
        # 验证参数
        if days < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_device_activity",
                details={"error": "统计天数必须为正整数", "days": days},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "统计天数必须为正整数"
            }), 400
        
        # 计算时间范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        print(f"[INFO] 设备活跃度统计时间范围: {start_date} 至 {end_date}")
        
        # 获取设备总数
        total_devices = Device.query.count()
        print(f"[INFO] 系统设备总数: {total_devices}")
        
        # 初始化统计数据
        device_stats = {}
        total_active_days = 0
        active_devices_set = set()
        
        # 初始化每日活跃数据
        daily_active_devices = {}
        
        # 初始化日期范围内的所有日期
        current_date = start_date
        while current_date <= end_date:
            date_str = current_date.strftime("%Y-%m-%d")
            daily_active_devices[date_str] = set()  # 初始化活跃设备集合
            current_date += timedelta(days=1)
        
        # 从MongoDB获取设备状态记录
        try:
            with mongo_collection(Config.MONGODB_COLLECTIONS.get("device_status", "device_status")) as collection:
                # 打印一下collection名称，确认正确
                print(f"[INFO] 正在查询MongoDB集合: {Config.MONGODB_COLLECTIONS.get('device_status', 'device_status')}")
                
                # 查询时间范围内所有设备状态记录
                # 根据device_bp.route('/v1/update_status')接口中的数据格式调整查询条件
                status_records = list(collection.find({
                    "timestamp": {"$gte": start_date, "$lte": end_date},
                    "power.state": {"$ne": "OFF"}  # 根据上报的设备状态数据格式调整查询条件
                }))
                
                print(f"[INFO] 找到设备状态记录总数: {len(status_records)}")
                
                # 如果没有找到记录，直接返回空结果
                if not status_records:
                    print("[WARNING] 未找到设备状态记录，返回空统计结果")
                    # 构建空的每日活跃数据
                    empty_daily_activity = []
                    current_date = start_date
                    while current_date <= end_date:
                        date_str = current_date.strftime("%Y-%m-%d")
                        empty_daily_activity.append({
                            "date": date_str,
                            "active_devices": 0
                        })
                        current_date += timedelta(days=1)
                    
                    # 构建空的周汇总数据
                    empty_weekly_summary = []
                    # 构建空的月汇总数据
                    empty_monthly_summary = []
                    
                    return jsonify({
                        "code": 0,
                        "message": "获取设备活跃度统计成功，但没有找到设备状态记录",
                        "data": {
                            "total_devices": total_devices,
                            "active_devices": 0,
                            "total_active_days": 0,
                            "days": days,
                            "daily_activity": empty_daily_activity,
                            "weekly_summary": empty_weekly_summary,
                            "monthly_summary": empty_monthly_summary,
                            "device_stats": []
                        }
                    }), 200
                
                # 处理每个设备的每日活跃状态
                # device_date_map 用于记录每个设备在每一天是否活跃
                device_date_map = {}
                
                for record in status_records:
                    device_id = record.get("device_id")
                    if not device_id:
                        continue
                        
                    # 获取记录的时间戳并转换为日期字符串
                    timestamp = record.get("timestamp")
                    if not timestamp or not hasattr(timestamp, "strftime"):
                        continue
                        
                    # 提取日期
                    record_date = timestamp.date()
                    date_str = record_date.strftime("%Y-%m-%d")
                    
                    # 确保日期在查询范围内
                    if record_date < start_date.date() or record_date > end_date.date():
                        continue
                    
                    # 初始化设备统计记录
                    if device_id not in device_stats:
                        device_stats[device_id] = {
                            "active_days": set(),
                            "last_active": None
                        }
                    
                    # 初始化设备-日期映射
                    if device_id not in device_date_map:
                        device_date_map[device_id] = set()
                    
                    # 如果这个设备在这一天还没有被记录为活跃
                    if date_str not in device_date_map[device_id]:
                        # 标记设备在这一天活跃
                        device_date_map[device_id].add(date_str)
                        
                        # 更新设备活跃天数
                        device_stats[device_id]["active_days"].add(date_str)
                        
                        # 更新每日活跃设备统计
                        daily_active_devices[date_str].add(device_id)
                        
                        # 增加总活跃天数计数
                        total_active_days += 1
                    
                    # 更新设备最后活跃时间
                    if not device_stats[device_id]["last_active"] or timestamp > device_stats[device_id]["last_active"]:
                        device_stats[device_id]["last_active"] = timestamp
                    
                    # 添加到活跃设备集合
                    active_devices_set.add(device_id)
                
        except Exception as e:
            print(f"[ERROR] 查询MongoDB设备状态记录异常: {str(e)}")
            import traceback
            traceback.print_exc()
            # 返回部分数据，而不是完全失败
            return jsonify({
                "code": 50001,
                "message": "获取设备状态记录异常，返回部分数据",
                "error": str(e),
                "data": {
                    "total_devices": total_devices,
                    "active_devices": 0,
                    "total_active_days": 0,
                    "days": days,
                    "daily_activity": [],
                    "weekly_summary": [],
                    "monthly_summary": [],
                    "device_stats": []
                }
            }), 500
        
        # 构建每日活跃数据列表
        daily_activity_list = []
        for date_str in sorted(daily_active_devices.keys()):
            daily_activity_list.append({
                "date": date_str,
                "active_devices": len(daily_active_devices[date_str])
            })
        
        # 构建周汇总数据
        weekly_summary = []
        # 按周分组
        current_week_start = start_date
        while current_week_start <= end_date:
            current_week_end = min(current_week_start + timedelta(days=6), end_date)
            week_str = f"第{(current_week_start - start_date).days // 7 + 1}周 ({current_week_start.strftime('%Y-%m-%d')} to {current_week_end.strftime('%Y-%m-%d')})"
            
            # 计算该周的活跃设备
            week_active_devices = set()
            
            current_date = current_week_start
            while current_date <= current_week_end:
                date_str = current_date.strftime("%Y-%m-%d")
                if date_str in daily_active_devices:
                    week_active_devices.update(daily_active_devices[date_str])
                current_date += timedelta(days=1)
            
            weekly_summary.append({
                "week": week_str,
                "active_devices": len(week_active_devices)
            })
            
            current_week_start += timedelta(days=7)
        
        # 构建月汇总数据
        monthly_summary = []
        # 按月分组
        months = {}
        for date_str in daily_active_devices:
            month_str = date_str[:7]  # 取YYYY-MM部分
            if month_str not in months:
                months[month_str] = set()
            months[month_str].update(daily_active_devices[date_str])
        
        for month_str in sorted(months.keys()):
            monthly_summary.append({
                "month": month_str,
                "active_devices": len(months[month_str])
            })
        
        # 获取设备详细信息并构建统计列表
        print(f"[INFO] 开始获取设备详细信息，活跃设备数: {len(active_devices_set)}")
        device_stats_list = []
        for device_id, stats in device_stats.items():
            try:
                device = Device.query.get(device_id)
                if device:
                    # 获取绑定的用户信息
                    user_info = {"user_id": None, "user_name": None}
                    if device.user_id:
                        user = User.query.get(device.user_id)
                        if user:
                            user_info = {
                                "user_id": user.user_id,
                                "user_name": user.user_name
                            }
                    
                    device_data = {
                        "device_id": device.device_id,
                        "user_id": user_info["user_id"],
                        "user_name": user_info["user_name"],
                        "active_days": len(stats["active_days"]),
                        "last_active": stats["last_active"].strftime("%Y-%m-%d %H:%M:%S") if stats["last_active"] else None
                    }
                    device_stats_list.append(device_data)
                    print(f"[INFO] 添加设备统计: {device.device_id}, 活跃天数: {len(stats['active_days'])}")
                else:
                    print(f"[WARNING] 未找到设备ID: {device_id}")
                    # 添加未找到设备的记录
                    device_stats_list.append({
                        "device_id": device_id,
                        "user_id": None,
                        "user_name": "未知",
                        "active_days": len(stats["active_days"]),
                        "last_active": stats["last_active"].strftime("%Y-%m-%d %H:%M:%S") if stats["last_active"] else None,
                        "note": "设备不存在于关系数据库中"
                    })
            except Exception as e:
                print(f"[ERROR] 处理设备 {device_id} 数据异常: {str(e)}")
                import traceback
                traceback.print_exc()
        
        # 按活跃天数降序排序
        device_stats_list.sort(key=lambda x: x["active_days"], reverse=True)
        
        print(f"[INFO] 最终统计: 活跃设备 {len(active_devices_set)}, 总活跃天数 {total_active_days}")
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取设备活跃度统计成功",
            "data": {
                "total_devices": total_devices,
                "active_devices": len(active_devices_set),
                "total_active_days": total_active_days,
                "days": days,
                "daily_activity": daily_activity_list,
                "weekly_summary": weekly_summary,
                "monthly_summary": monthly_summary,
                "device_stats": device_stats_list
            }
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="query_device_activity",
            details={
                "days": days,
                "total_devices": total_devices,
                "active_devices": len(active_devices_set),
                "total_active_days": total_active_days
            },
            status="success",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取设备活跃度统计异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_device_activity",
            details={"error": str(e)},
            status="failed",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/music_overview', methods=['GET'])
@admin_required
def get_music_overview(admin_id, admin_level):
    """
    获取音乐播放概览统计数据接口
    请求示例：/api/v1/admin/music_overview?days=30
    
    参数说明：
    - days: 统计天数，默认为30天
    
    返回格式：
    {
        "code": 0,
        "message": "获取音乐播放概览成功",
        "data": {
            "total_plays": 总播放次数,
            "unique_songs": 不同歌曲数量,
            "top_songs": [
                {
                    "song_id": 歌曲ID,
                    "song_name": 歌曲名称,
                    "artist": 艺术家,
                    "play_count": 播放次数
                },
                ...
            ],
            "top_artists": [
                {
                    "artist": 艺术家名称,
                    "play_count": 播放次数,
                    "song_count": 歌曲数量
                },
                ...
            ],
            "daily_trend": [
                {
                    "date": 日期,
                    "play_count": 播放次数
                },
                ...
            ]
        }
    }
    """
    try:
        # 记录操作开始
        log_admin_operation(
            admin_id=admin_id,
            operation="query_music_overview",
            details={"action": "开始查询音乐播放概览"},
            status="started",
            resource_type="statistics",
            resource_id=None
        )
        
        # 获取天数参数
        days = request.args.get('days', 30, type=int)
        
        # 验证参数
        if days < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_music_overview",
                details={"error": "统计天数必须为正整数", "days": days},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "统计天数必须为正整数"
            }), 400
        
        # 计算时间范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        print(f"[INFO] 音乐概览统计时间范围: {start_date} 至 {end_date}")
        
        # 预先从数据库加载歌曲信息和艺术家信息，减少重复查询
        songs_dict = {}
        artists_dict = {}
        artist_song_relations = {}
        
        try:
            # 1. 加载所有艺术家信息
            all_artists = Artist.query.all()
            for artist in all_artists:
                artists_dict[artist.artist_id] = artist.artist_name
            print(f"[INFO] 预加载了 {len(artists_dict)} 位艺术家信息")
            
            # 2. 加载艺术家与歌曲的关联关系
            artist_song_relations_list = db.session.query(ArtistSong).all()
            for relation in artist_song_relations_list:
                if relation.song_id not in artist_song_relations:
                    artist_song_relations[relation.song_id] = []
                artist_song_relations[relation.song_id].append(relation.artist_id)
            print(f"[INFO] 预加载了 {len(artist_song_relations)} 首歌曲的艺术家关联关系")
            
            # 3. 加载所有歌曲信息
            all_songs = Song.query.all()
            for song in all_songs:
                # 获取歌曲关联的艺术家
                artist_ids = artist_song_relations.get(song.song_id, [])
                artist_names = []
                for artist_id in artist_ids:
                    artist_name = artists_dict.get(artist_id)
                    if artist_name:
                        artist_names.append(artist_name)
                
                songs_dict[song.song_id] = {
                    "song_name": song.song_name,
                    "artist_ids": artist_ids,
                    "artist_names": artist_names
                }
            print(f"[INFO] 预加载了 {len(songs_dict)} 首歌曲信息")
        except Exception as e:
            print(f"[WARNING] 预加载数据库信息失败: {str(e)}")
            import traceback
            traceback.print_exc()
        
        # 从MongoDB获取播放记录
        try:
            # 首先尝试查询listen_records集合
            collection_name = Config.MONGODB_COLLECTIONS.get("listen_records", "listen_records")
            print(f"[INFO] 尝试查询MongoDB集合: {collection_name}")
            
            # 使用日期查询条件
            date_end = end_date.strftime("%Y-%m-%d")
            date_start = start_date.strftime("%Y-%m-%d")
            
            with mongo_collection(collection_name) as collection:
                play_records = list(collection.find({
                    "date": {"$gte": date_start, "$lte": date_end}
                }))
                
                print(f"[INFO] 使用date字段查询到记录数量: {len(play_records)}")
                
                # 如果找不到记录，尝试使用timestamp字段和play_history集合
                if not play_records:
                    print(f"[INFO] 未找到记录，尝试使用timestamp字段查询")
                    
                    with mongo_collection(Config.MONGODB_COLLECTIONS.get("play_history", "play_history")) as history_collection:
                        play_records = list(history_collection.find({
                            "timestamp": {"$gte": start_date, "$lte": end_date}
                        }))
                        
                        print(f"[INFO] 使用timestamp字段查询到记录数量: {len(play_records)}")
                
                # 如果仍然没有记录，返回空结果
                if not play_records:
                    print("[WARNING] 未找到播放记录，返回空统计")
                    # 返回空的统计结果而不是错误
                    return jsonify({
                        "code": 0,
                        "message": "获取音乐播放概览成功，但没有找到播放记录",
                        "data": {
                            "total_plays": 0,
                            "unique_songs": 0,
                            "top_songs": [],
                            "top_artists": [],
                            "daily_trend": []
                        }
                    }), 200
                
                # 打印几条记录示例以便调试
                sample_records = play_records[:3] if len(play_records) >= 3 else play_records
                for i, record in enumerate(sample_records):
                    print(f"[DEBUG] 示例记录{i+1}: {record}")
                
                # 计算总播放次数
                total_plays = len(play_records)
                
                # 统计不同歌曲
                unique_songs = set()
                song_play_counts = {}
                artist_play_counts = {}
                artist_songs = {}
                daily_plays = {}
                
                for record in play_records:
                    # 获取歌曲信息
                    song_id = record.get("song_id")
                    song_name = record.get("song_name", "未知歌曲")
                    
                    # 获取艺术家信息 - 多重查找逻辑
                    artist = None
                    artist_id = record.get("artist_id")  # 尝试从记录中获取艺术家ID
                    
                    # 1. 如果记录中有艺术家ID，从预加载的艺术家字典中查找
                    if artist_id and artist_id in artists_dict:
                        artist = artists_dict[artist_id]
                        print(f"[INFO] 通过艺术家ID {artist_id} 获取到艺术家: {artist}")
                    
                    # 2. 尝试从记录中获取艺术家名称
                    if not artist and "artist" in record and record["artist"] and record["artist"] != "未知艺术家":
                        artist = record["artist"]
                        print(f"[INFO] 从记录中获取到艺术家名称: {artist}")
                    
                    # 3. 尝试从记录中的artists字段获取（可能是数组）
                    if not artist and "artists" in record and record["artists"]:
                        artists_data = record["artists"]
                        if isinstance(artists_data, list) and len(artists_data) > 0:
                            if isinstance(artists_data[0], dict) and "artist_name" in artists_data[0]:
                                artist = artists_data[0]["artist_name"]
                            else:
                                artist = str(artists_data[0])
                            print(f"[INFO] 从记录的artists数组获取到艺术家: {artist}")
                    
                    # 4. 尝试从预加载的歌曲信息中获取
                    if not artist and song_id in songs_dict and songs_dict[song_id]["artist_names"]:
                        artist = songs_dict[song_id]["artist_names"][0]
                        print(f"[INFO] 从预加载的歌曲-艺术家关系中获取到艺术家: {artist}")
                    
                    # 5. 如果仍然没有找到，尝试直接从数据库查询
                    if not artist and song_id:
                        try:
                            # 查询歌曲-艺术家关系
                            artist_song_rel = db.session.query(ArtistSong).filter(ArtistSong.song_id == song_id).first()
                            if artist_song_rel:
                                artist_info = Artist.query.get(artist_song_rel.artist_id)
                                if artist_info:
                                    artist = artist_info.artist_name
                                    print(f"[INFO] 从数据库查询获取到艺术家: {artist}")
                        except Exception as e:
                            print(f"[WARNING] 数据库查询艺术家信息异常: {str(e)}, 歌曲ID: {song_id}")
                    
                    # 6. 最后才使用默认值
                    if not artist:
                        artist = "未知艺术家"
                        print(f"[INFO] 使用默认艺术家'未知艺术家'")
                    
                    # 尝试获取日期信息
                    date_str = None
                    timestamp = record.get("timestamp")
                    if timestamp and hasattr(timestamp, "strftime"):
                        date_str = timestamp.strftime("%Y-%m-%d")
                    else:
                        # 如果没有timestamp字段或不是日期对象，尝试从date字段获取
                        date_str = record.get("date")
                    
                    if not song_id:
                        print(f"[WARNING] 跳过无歌曲ID的记录: {song_name}")
                        continue
                    
                    if not date_str:
                        print(f"[WARNING] 跳过无日期的记录: {song_id} - {song_name}")
                        continue
                    
                    # 打印调试信息
                    print(f"[DEBUG] 处理播放记录: {song_name}, 艺术家: {artist}, 日期: {date_str}")
                    
                    # 添加到唯一歌曲集合
                    unique_songs.add(song_id)
                    
                    # 更新歌曲播放次数
                    song_key = f"{song_id}_{song_name}"
                    if song_key in song_play_counts:
                        song_play_counts[song_key]["play_count"] += 1
                    else:
                        song_play_counts[song_key] = {
                            "song_id": song_id,
                            "song_name": song_name,
                            "artist": artist,
                            "play_count": 1
                        }
                    
                    # 更新艺术家播放次数
                    if artist:
                        if artist in artist_play_counts:
                            artist_play_counts[artist] += 1
                        else:
                            artist_play_counts[artist] = 1
                        
                        # 更新艺术家歌曲集合
                        if artist not in artist_songs:
                            artist_songs[artist] = set()
                        artist_songs[artist].add(song_id)
                    
                    # 更新每日播放统计
                    try:
                        if date_str in daily_plays:
                            daily_plays[date_str] += 1
                        else:
                            daily_plays[date_str] = 1
                    except Exception as e:
                        print(f"[WARNING] 处理日期失败: {str(e)}, date_str: {date_str}, 类型: {type(date_str)}")
                
                # 构建热门歌曲列表（前10首）
                top_songs = sorted(song_play_counts.values(), key=lambda x: x["play_count"], reverse=True)[:10]
                
                # 构建热门艺术家列表（前10个）
                top_artists = []
                for artist, play_count in artist_play_counts.items():
                    top_artists.append({
                        "artist": artist,
                        "play_count": play_count,
                        "song_count": len(artist_songs.get(artist, set()))
                    })
                top_artists = sorted(top_artists, key=lambda x: x["play_count"], reverse=True)[:10]
                
                # 构建每日播放趋势
                daily_trend = []
                # 确保有完整的日期范围，即使某天没有播放记录
                current_date = start_date
                while current_date <= end_date:
                    date_str = current_date.strftime("%Y-%m-%d")
                    daily_trend.append({
                        "date": date_str,
                        "play_count": daily_plays.get(date_str, 0)
                    })
                    current_date += timedelta(days=1)
                
                print(f"[INFO] 统计结果: 总播放次数 {total_plays}, 唯一歌曲 {len(unique_songs)}, 艺术家 {len(artist_play_counts)}")
                
                # 构建响应数据
                response = {
                    "code": 0,
                    "message": "获取音乐播放概览成功",
                    "data": {
                        "total_plays": total_plays,
                        "unique_songs": len(unique_songs),
                        "top_songs": top_songs,
                        "top_artists": top_artists,
                        "daily_trend": daily_trend
                    }
                }
                
                # 记录操作成功
                log_admin_operation(
                    admin_id=admin_id,
                    operation="query_music_overview",
                    details={
                        "days": days,
                        "total_plays": total_plays,
                        "unique_songs": len(unique_songs),
                        "top_songs_count": len(top_songs),
                        "top_artists_count": len(top_artists)
                    },
                    status="success",
                    resource_type="statistics",
                    resource_id=None
                )
                
                return jsonify(response), 200
                
        except Exception as e:
            print(f"[ERROR] 查询MongoDB播放记录异常: {str(e)}")
            import traceback
            traceback.print_exc()
            
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_music_overview",
                details={"error": str(e), "part": "MongoDB查询"},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            
            # 返回部分数据而不是完全失败
            return jsonify({
                "code": 50001,
                "message": "获取播放记录异常，返回部分数据",
                "error": str(e),
                "data": {
                    "total_plays": 0,
                    "unique_songs": 0,
                    "top_songs": [],
                    "top_artists": [],
                    "daily_trend": []
                }
            }), 500
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取音乐播放概览异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_music_overview",
            details={"error": str(e)},
            status="failed",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/listening_time_distribution', methods=['GET'])
@admin_required
def get_listening_time_distribution(admin_id, admin_level):
    """
    获取用户听歌时段分布统计数据接口
    请求示例：/api/v1/admin/listening_time_distribution?days=30
    
    参数说明：
    - days: 统计天数，默认为30天
    
    返回格式：
    {
        "code": 0,
        "message": "获取用户听歌时段分布成功",
        "data": {
            "weekday_hourly_distribution": [
                {
                    "weekday": 0,  # 0-6，0表示周一，6表示周日
                    "weekday_name": "周一",
                    "hourly_data": [
                        {
                            "hour": 0,  # 0-23小时
                            "play_count": 该小时段内的播放次数,
                            "play_duration": 该小时段内的播放总时长(秒),
                            "avg_duration": 该小时段内的平均播放时长(秒)
                        },
                        ...
                    ]
                },
                ...
            ]
        }
    }
    """
    try:
        # 记录操作开始
        log_admin_operation(
            admin_id=admin_id,
            operation="query_listening_distribution",
            details={"action": "开始查询听歌时段分布"},
            status="started",
            resource_type="statistics",
            resource_id=None
        )
        
        # 获取天数参数
        days = request.args.get('days', 30, type=int)
        
        # 验证参数
        if days < 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_listening_distribution",
                details={"error": "统计天数必须为正整数", "days": days},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "统计天数必须为正整数"
            }), 400
        
        # 计算时间范围
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        print(f"[INFO] 听歌时段分布统计时间范围: {start_date} 至 {end_date}")
        
        # 定义时段划分
        day_periods = {
            "morning": (6, 11),    # 6:00-11:59
            "afternoon": (12, 17), # 12:00-17:59
            "evening": (18, 22),   # 18:00-22:59
            "night": (23, 5)       # 23:00-5:59
        }
        
        # 定义星期几名称
        weekday_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
        
        # 预加载所有用户
        all_users = User.query.all()
        # 创建两种映射：字符串ID到用户 和 整数ID到用户
        str_user_dict = {}
        int_user_dict = {}
        
        for user in all_users:
            str_id, int_id = normalize_user_id(user.user_id)
            if str_id:
                str_user_dict[str_id] = user
            if int_id is not None:
                int_user_dict[int_id] = user
                
        print(f"[INFO] 预加载了 {len(all_users)} 个用户信息")
        
        # 从MongoDB获取播放记录
        try:
            # 首先尝试查询listen_records集合
            collection_name = Config.MONGODB_COLLECTIONS.get("listen_records", "listen_records")
            print(f"[INFO] 尝试查询MongoDB集合: {collection_name}")
            
            # 使用日期查询条件
            date_end = end_date.strftime("%Y-%m-%d")
            date_start = start_date.strftime("%Y-%m-%d")
            
            with mongo_collection(collection_name) as collection:
                play_records = list(collection.find({
                    "date": {"$gte": date_start, "$lte": date_end}
                }))
                
                print(f"[INFO] 使用date字段查询到记录数量: {len(play_records)}")
                
                # 如果找不到记录，尝试使用timestamp字段和play_history集合
                if not play_records:
                    print(f"[INFO] 未找到记录，尝试使用timestamp字段查询")
                    
                    with mongo_collection(Config.MONGODB_COLLECTIONS.get("play_history", "play_history")) as history_collection:
                        play_records = list(history_collection.find({
                            "timestamp": {"$gte": start_date, "$lte": end_date}
                        }))
                        
                        print(f"[INFO] 使用timestamp字段查询到记录数量: {len(play_records)}")
                
                # 打印几条记录示例以便调试
                sample_records = play_records[:3] if len(play_records) >= 3 else play_records
                for i, record in enumerate(sample_records):
                    print(f"[DEBUG] 示例记录{i+1}: {record}")
                
                # 检查是否有记录
                if not play_records:
                    print("[WARNING] 未找到播放记录，返回空统计")
                    # 返回空的统计结果而不是错误
                    return jsonify({
                        "code": 0,
                        "message": "获取用户听歌时段分布成功，但没有找到播放记录",
                        "data": {
                            "weekday_hourly_distribution": []
                        }
                    }), 200
                
                # 初始化统计数据
                total_plays = len(play_records)
                total_duration = 0
                hourly_counts = {hour: 0 for hour in range(24)}  # 初始化24小时的计数器
                hourly_durations = {hour: 0 for hour in range(24)}  # 初始化24小时的时长统计
                period_counts = {period: 0 for period in day_periods.keys()}  # 初始化时段计数器
                period_durations = {period: 0 for period in day_periods.keys()}  # 初始化时段时长统计
                weekday_counts = {weekday: 0 for weekday in range(7)}  # 初始化星期几计数器
                weekday_durations = {weekday: 0 for weekday in range(7)}  # 初始化星期几时长统计
                
                # 初始化星期几和小时的二维数据
                weekday_hourly_counts = {weekday: {hour: 0 for hour in range(24)} for weekday in range(7)}
                weekday_hourly_durations = {weekday: {hour: 0 for hour in range(24)} for weekday in range(7)}
                
                # 初始化用户听歌时段统计
                user_play_counts = {}  # 用户总播放次数
                user_play_durations = {}  # 用户总播放时长
                user_hour_counts = {}  # 用户各小时段播放次数
                user_hour_durations = {}  # 用户各小时段播放时长
                user_period_counts = {}  # 用户各时段播放次数
                user_period_durations = {}  # 用户各时段播放时长
                
                # 遍历播放记录，统计时段数据
                for record in play_records:
                    # 获取相关信息
                    user_id = record.get("user_id")
                    duration = record.get("duration", 0)  # 获取播放时长，默认为0
                    
                    # 尝试将持续时间转换为整数
                    try:
                        if duration is not None:
                            duration = int(duration)
                        else:
                            duration = 0
                    except (ValueError, TypeError):
                        duration = 0
                    
                    # 累加总播放时长
                    total_duration += duration
                    
                    # 尝试获取时间信息
                    play_time = None
                    timestamp = record.get("timestamp")
                    if timestamp and hasattr(timestamp, "strftime"):
                        play_time = timestamp
                    else:
                        # 如果没有timestamp字段或不是日期对象，尝试从其他字段获取
                        date_str = record.get("date")
                        time_str = record.get("time")
                        if date_str and time_str:
                            try:
                                play_time = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M:%S")
                            except (ValueError, TypeError):
                                print(f"[WARNING] 无法解析日期时间: {date_str} {time_str}")
                    
                    if not play_time:
                        print(f"[WARNING] 跳过无时间信息的记录")
                        continue
                    
                    # 标准化用户ID
                    str_id, int_id = normalize_user_id(user_id)
                    if not str_id:
                        print(f"[WARNING] 无法标准化用户ID: {user_id}")
                        continue
                    
                    # 提取小时、星期几
                    hour = play_time.hour
                    weekday = play_time.weekday()  # 0-6，0表示周一
                    
                    # 更新小时分布统计
                    hourly_counts[hour] += 1
                    hourly_durations[hour] += duration
                    
                    # 更新星期几和小时的二维分布统计
                    weekday_hourly_counts[weekday][hour] += 1
                    weekday_hourly_durations[weekday][hour] += duration
                    
                    # 更新时段分布统计
                    for period, (start_hour, end_hour) in day_periods.items():
                        if period == "night":
                            # 特殊处理夜晚时段，因为跨越了0点
                            if hour >= 23 or hour <= 5:
                                period_counts[period] += 1
                                period_durations[period] += duration
                                break
                        elif start_hour <= hour <= end_hour:
                            period_counts[period] += 1
                            period_durations[period] += duration
                            break
                    
                    # 更新星期几分布统计
                    weekday_counts[weekday] += 1
                    weekday_durations[weekday] += duration
                    
                    # 更新用户听歌时段统计
                    # 更新用户总播放次数和总时长
                    if str_id in user_play_counts:
                        user_play_counts[str_id] += 1
                        user_play_durations[str_id] += duration
                    else:
                        user_play_counts[str_id] = 1
                        user_play_durations[str_id] = duration
                    
                    # 更新用户小时分布
                    if str_id not in user_hour_counts:
                        user_hour_counts[str_id] = {hour: 0 for hour in range(24)}
                        user_hour_durations[str_id] = {hour: 0 for hour in range(24)}
                    user_hour_counts[str_id][hour] += 1
                    user_hour_durations[str_id][hour] += duration
                    
                    # 更新用户时段分布
                    if str_id not in user_period_counts:
                        user_period_counts[str_id] = {period: 0 for period in day_periods.keys()}
                        user_period_durations[str_id] = {period: 0 for period in day_periods.keys()}
                    
                    # 确定当前时段
                    current_period = None
                    for period, (start_hour, end_hour) in day_periods.items():
                        if period == "night":
                            if hour >= 23 or hour <= 5:
                                current_period = period
                                break
                        elif start_hour <= hour <= end_hour:
                            current_period = period
                            break
                    
                    if current_period:
                        user_period_counts[str_id][current_period] += 1
                        user_period_durations[str_id][current_period] += duration
                
                # 构建小时分布数据
                hourly_distribution = []
                for hour, count in hourly_counts.items():
                    duration = hourly_durations[hour]
                    percentage = (count / total_plays) * 100 if total_plays > 0 else 0
                    avg_duration = duration / count if count > 0 else 0
                    hourly_distribution.append({
                        "hour": hour,
                        "play_count": count,
                        "play_duration": duration,
                        "avg_duration": round(avg_duration, 2),
                        "percentage": round(percentage, 2)
                    })
                
                # 构建时段分布数据
                day_period_distribution = {}
                for period, count in period_counts.items():
                    duration = period_durations[period]
                    percentage = (count / total_plays) * 100 if total_plays > 0 else 0
                    avg_duration = duration / count if count > 0 else 0
                    day_period_distribution[period] = {
                        "play_count": count,
                        "play_duration": duration,
                        "avg_duration": round(avg_duration, 2),
                        "percentage": round(percentage, 2)
                    }
                
                # 构建星期几分布数据
                weekday_distribution = []
                for weekday, count in weekday_counts.items():
                    duration = weekday_durations[weekday]
                    percentage = (count / total_plays) * 100 if total_plays > 0 else 0
                    avg_duration = duration / count if count > 0 else 0
                    weekday_distribution.append({
                        "weekday": weekday,
                        "weekday_name": weekday_names[weekday],
                        "play_count": count,
                        "play_duration": duration,
                        "avg_duration": round(avg_duration, 2),
                        "percentage": round(percentage, 2)
                    })
                
                # 构建星期几和小时的二维数据
                weekday_hourly_distribution = []
                for weekday in range(7):
                    hourly_data = []
                    for hour in range(24):
                        count = weekday_hourly_counts[weekday][hour]
                        duration = weekday_hourly_durations[weekday][hour]
                        avg_duration = duration / count if count > 0 else 0
                        hourly_data.append({
                            "hour": hour,
                            "play_count": count,
                            "play_duration": duration,
                            "avg_duration": round(avg_duration, 2)
                        })
                    
                    weekday_hourly_distribution.append({
                        "weekday": weekday,
                        "weekday_name": weekday_names[weekday],
                        "hourly_data": hourly_data
                    })
                
                # 构建用户时段偏好数据
                user_time_preferences = []
                print(f"[INFO] 开始处理用户时段偏好，活跃用户数: {len(user_hour_counts)}")
                
                for user_id, hours in user_hour_counts.items():
                    try:
                        # 尝试找到对应的用户
                        user = None
                        
                        # 先尝试从字符串ID映射中获取
                        if user_id in str_user_dict:
                            user = str_user_dict[user_id]
                        
                        # 如果找不到，尝试从整数ID映射中获取
                        elif user_id.isdigit() and int(user_id) in int_user_dict:
                            user = int_user_dict[int(user_id)]
                        
                        if not user:
                            print(f"[WARNING] 未找到用户ID: {user_id}")
                            continue
                        
                        print(f"[INFO] 处理用户时段偏好: {user.user_name}")
                        user_total_plays = user_play_counts.get(user_id, 0)
                        user_total_duration = user_play_durations.get(user_id, 0)
                        user_avg_duration = user_total_duration / user_total_plays if user_total_plays > 0 else 0
                        
                        # 找出用户最喜欢的小时（播放次数最多的前3个小时）
                        favorite_hours = sorted(hours.items(), key=lambda x: x[1], reverse=True)[:3]
                        favorite_hours = [hour for hour, _ in favorite_hours if hours[hour] > 0]
                        
                        # 找出用户最喜欢的时段
                        periods = user_period_counts.get(user_id, {})
                        favorite_period = max(periods.items(), key=lambda x: x[1])[0] if periods else None
                        
                        user_time_preferences.append({
                            "user_id": user.user_id,
                            "user_name": user.user_name,
                            "total_plays": user_total_plays,
                            "total_duration": user_total_duration,
                            "avg_duration": round(user_avg_duration, 2),
                            "favorite_hours": favorite_hours,
                            "favorite_period": favorite_period
                        })
                    except Exception as e:
                        print(f"[ERROR] 处理用户 {user_id} 时段偏好异常: {str(e)}")
                        import traceback
                        traceback.print_exc()
                
                # 按用户总播放次数降序排序
                user_time_preferences.sort(key=lambda x: x["total_plays"], reverse=True)
                
                print(f"[INFO] 统计结果: 总播放次数 {total_plays}, 总播放时长 {total_duration}, 处理用户 {len(user_time_preferences)}")
                
                # 构建响应数据
                response = {
                    "code": 0,
                    "message": "获取用户听歌时段分布成功",
                    "data": {
                        "weekday_hourly_distribution": weekday_hourly_distribution
                    }
                }
                
                # 记录操作成功
                log_admin_operation(
                    admin_id=admin_id,
                    operation="query_listening_distribution",
                    details={
                        "days": days,
                        "total_plays": total_plays,
                        "total_duration": total_duration,
                        "user_count": len(user_time_preferences)
                    },
                    status="success",
                    resource_type="statistics",
                    resource_id=None
                )
                
                return jsonify(response), 200
            
        except Exception as e:
            print(f"[ERROR] 查询MongoDB播放记录异常: {str(e)}")
            import traceback
            traceback.print_exc()
            
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="query_listening_distribution",
                details={"error": str(e), "part": "MongoDB查询"},
                status="failed",
                resource_type="statistics",
                resource_id=None
            )
            
                            # 返回部分数据而不是完全失败
            return jsonify({
                "code": 50001,
                "message": "获取播放记录异常，返回部分数据",
                "error": str(e),
                "data": {
                    "weekday_hourly_distribution": []
                }
            }), 500
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取用户听歌时段分布异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_listening_distribution",
            details={"error": str(e)},
            status="failed",
            resource_type="statistics",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/get_my_logs', methods=['GET'])
@admin_required
def get_admin_self_logs(admin_id, admin_level):
    """
    获取管理员自身账号活动日志接口
    请求示例：/api/v1/admin/get_my_logs?page=1&page_size=20
    
    参数说明：
    - page: 页码，默认为1
    - page_size: 每页返回的日志数量，默认为50条，最大200条
    
    返回格式：
    {
        "code": 0,
        "message": "获取管理员日志成功",
        "data": {
            "admin_id": 管理员ID,
            "admin_name": 管理员名称,
            "admin_level": 管理员级别,
            "pagination": {
                "page": 当前页码,
                "page_size": 每页数量,
                "total_logs": 总日志数量,
                "total_pages": 总页数
            },
            "logs": [
                {
                    "operation": 操作类型,
                    "timestamp": 操作时间,
                    "ip": IP地址,
                    "details": 操作详情,
                    "status": 操作状态
                },
                ...
            ]
        }
    }
    """
    try:
        # 获取参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 50, type=int)
        
        # 验证参数
        if page < 1:
            return jsonify({
                "code": 40010,
                "message": "页码必须大于0"
            }), 400
            
        if page_size < 1 or page_size > 200:
            return jsonify({
                "code": 40010,
                "message": "每页日志数量必须在1-200之间"
            }), 400
        
        # 获取当前管理员信息
        current_admin = Admin.query.get(admin_id)
        if not current_admin:
            return jsonify({
                "code": 40400,
                "message": "未找到管理员信息"
            }), 404
        
        # 从MongoDB获取管理员活动日志
        logs = []
        total_logs = 0
        try:
            # 使用正确的集合名称 - admin_logs 而非 admin_operations
            collection_name = Config.MONGODB_COLLECTIONS.get("admin_logs", "admin_logs")
            print(f"[INFO] 查询管理员日志，使用集合: {collection_name}")
            
            with mongo_collection(collection_name) as collection:
                # 构建查询条件，同时处理整数和字符串类型的admin_id
                query_conditions = []
                
                # 如果是整数ID
                if isinstance(admin_id, int):
                    query_conditions.append({"admin_id": admin_id})
                    query_conditions.append({"admin_id": str(admin_id)})
                # 如果是字符串ID但可以转为整数
                elif isinstance(admin_id, str) and admin_id.isdigit():
                    query_conditions.append({"admin_id": admin_id})
                    query_conditions.append({"admin_id": int(admin_id)})
                # 其他情况只用字符串查询
                else:
                    query_conditions.append({"admin_id": admin_id})
                
                # 使用$or条件组合查询
                query = {"$or": query_conditions}
                print(f"[INFO] 查询条件: {query}")
                
                # 先获取总数量
                total_logs = collection.count_documents(query)
                
                # 计算跳过的文档数量
                skip = (page - 1) * page_size
                
                # 查询指定管理员的活动记录，支持分页
                admin_logs = collection.find(
                    query,
                    sort=[("timestamp", -1)],
                    skip=skip,
                    limit=page_size
                )
                
                # 转换为列表并格式化数据
                for log in admin_logs:
                    # 处理ObjectId，将其转为字符串
                    log["_id"] = str(log["_id"])
                    
                    # 格式化时间
                    if "timestamp" in log and isinstance(log["timestamp"], datetime):
                        log["timestamp"] = log["timestamp"].strftime("%Y-%m-%d %H:%M:%S")
                    
                    logs.append(log)
                    
                print(f"[INFO] 找到管理员 {admin_id} 的日志记录 {len(logs)} 条，总数: {total_logs}")
        except Exception as e:
            print(f"[ERROR] 查询管理员日志异常: {str(e)}")
            import traceback
            traceback.print_exc()
            return jsonify({
                "code": 50001,
                "message": f"查询日志异常: {str(e)}"
            }), 500
        
        # 计算总页数
        total_pages = (total_logs + page_size - 1) // page_size
        
        # 记录此次查询操作
        log_admin_operation(
            admin_id=admin_id,
            operation="query_self_logs",
            details={
                "page": page, 
                "page_size": page_size, 
                "found_logs": len(logs),
                "total_logs": total_logs
            },
            status="success",
            resource_type="admin_logs",
            resource_id=admin_id
        )
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取管理员日志成功",
            "data": {
                "admin_id": current_admin.admin_id,
                "admin_name": current_admin.admin_name,
                "admin_level": current_admin.admin_level,
                "pagination": {
                    "page": page,
                    "page_size": page_size,
                    "total_logs": total_logs,
                    "total_pages": total_pages
                },
                "logs": logs
            }
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取管理员日志异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="query_self_logs",
            details={"error": str(e)},
            status="failed",
            resource_type="admin_logs",
            resource_id=admin_id
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/delete', methods=['DELETE'])
@admin_required
def delete_admin(admin_id, admin_level):
    """
    删除管理员接口
    请求示例：
    {
        "target_admin_name": "test8",  // 要删除的管理员名称
        "current_admin_name": "dxj",   // 当前管理员名称(可选,用于二次验证)
        "current_admin_password": "123456"  // 当前管理员密码(可选,用于二次验证)
    }
    
    返回格式：
    {
        "code": 0,
        "message": "删除管理员成功",
        "data": {
            "deleted_admin_id": 2,
            "deleted_admin_name": "管理员名称"
        }
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "请求数据为空"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify(
                code=40000,
                message="请求数据为空"
            ), 400
        
        # 获取请求参数
        target_admin_name = data.get('target_admin_name')
        current_admin_name = data.get('current_admin_name')
        current_admin_password = data.get('current_admin_password')
        
        # 验证参数
        if not target_admin_name:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "未提供目标管理员名称"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify(
                code=40010,
                message="请提供目标管理员名称"
            ), 400
        
        # 获取当前管理员信息
        current_admin = Admin.query.get(admin_id)
        if not current_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "当前管理员不存在"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify(
                code=40100,
                message="当前管理员不存在"
            ), 401
        
        # 如果提供了当前管理员名称，验证是否匹配
        if current_admin_name and current_admin_name != current_admin.admin_name:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "当前管理员名称不匹配"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify(
                code=40100,
                message="当前管理员名称不匹配"
            ), 401
        
        # 如果提供了当前管理员密码，验证密码是否正确
        if current_admin_password:
            import bcrypt
            if not bcrypt.checkpw(current_admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="delete_admin",
                    details={"error": "当前管理员密码不正确"},
                    status="failed",
                    resource_type="admins",
                    resource_id=None
                )
                return jsonify(
                    code=40101,
                    message="当前管理员密码不正确"
                ), 401
        
        # 获取目标管理员信息
        target_admin = Admin.query.filter_by(admin_name=target_admin_name).first()
        if not target_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "目标管理员不存在", "target_admin_name": target_admin_name},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify(
                code=40400,
                message="目标管理员不存在"
            ), 404
        
        # 保存目标管理员ID用于后续记录
        target_admin_id = target_admin.admin_id
        
        # 检查特殊权限规则
        
        # 规则1: 只有0级管理员可以删除0级管理员
        if target_admin.admin_level == 0 and current_admin.admin_level != 0:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={
                    "error": "权限不足，只有0级管理员可以删除0级管理员", 
                    "current_level": current_admin.admin_level, 
                    "target_level": target_admin.admin_level,
                    "target_admin_name": target_admin_name,
                    "target_admin_id": target_admin_id
                },
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify(
                code=40300,
                message="权限不足，只有0级管理员可以删除0级管理员"
            ), 403
            
        # 规则2: 1级管理员不能删除1级管理员
        if current_admin.admin_level == 1 and target_admin.admin_level == 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={
                    "error": "权限不足，1级管理员不能删除1级管理员", 
                    "current_level": current_admin.admin_level, 
                    "target_level": target_admin.admin_level,
                    "target_admin_name": target_admin_name,
                    "target_admin_id": target_admin_id
                },
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify(
                code=40300,
                message="权限不足，1级管理员不能删除1级管理员"
            ), 403
        
        # 规则3: 普通权限检查 - 只能删除级别比自己低的管理员
        if current_admin.admin_level >= target_admin.admin_level:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={
                    "error": "权限不足，无法删除同级或更高级别的管理员", 
                    "current_level": current_admin.admin_level, 
                    "target_level": target_admin.admin_level,
                    "target_admin_name": target_admin_name,
                    "target_admin_id": target_admin_id
                },
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify(
                code=40300,
                message="权限不足，无法删除同级或更高级别的管理员"
            ), 403
        
        # 不能删除ID为1的超级管理员
        if target_admin.admin_id == 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="delete_admin",
                details={"error": "不能删除超级管理员", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify(
                code=40300,
                message="不能删除超级管理员"
            ), 403
        
        # 保存要删除的管理员信息用于日志记录
        deleted_admin_info = {
            "admin_id": target_admin.admin_id,
            "admin_name": target_admin.admin_name,
            "admin_level": target_admin.admin_level,
            "create_at": target_admin.create_at.strftime("%Y-%m-%d %H:%M:%S") if target_admin.create_at else None
        }
        
        # 执行删除操作
        db.session.delete(target_admin)
        db.session.commit()
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_admin",
            details={
                "deleted_admin": deleted_admin_info
            },
            status="success",
            resource_type="admins",
            resource_id=target_admin_id
        )
        
        # 记录MongoDB日志
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin_id,
                "admin_name": current_admin.admin_name,
                "operation": "delete_admin",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "status": "success",
                "details": {
                    "target_admin_id": target_admin_id,
                    "target_admin_name": deleted_admin_info["admin_name"]
                }
            })
        
        return jsonify(
            code=0,
            message="删除管理员成功",
            data={
                "deleted_admin_id": deleted_admin_info["admin_id"],
                "deleted_admin_name": deleted_admin_info["admin_name"]
            }
        ), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 删除管理员异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="delete_admin",
            details={"error": str(e), "target_admin_name": target_admin_name if 'target_admin_name' in locals() else None},
            status="failed",
            resource_type="admins",
            resource_id=target_admin_id if 'target_admin_id' in locals() else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@admin_bp.route('/v1/admin/changeauthority', methods=['POST'])
@admin_required
def change_admin_authority(admin_id, admin_level):
    """
    修改管理员权限级别接口
    请求示例：
    {
        "target_admin_id": 3,  # 要修改的管理员ID
        "new_level": 2,  # 新的权限级别(0-3)
        "current_admin_password": "password123"  # 当前管理员密码(验证身份)
    }
    
    返回格式：
    {
        "code": 0,
        "message": "修改管理员权限成功",
        "data": {
            "admin_id": 3,
            "admin_name": "管理员名称",
            "previous_level": 3,
            "new_level": 2
        }
    }
    """
    try:
        # 1. 检查当前管理员权限级别
        # 只有0级和1级管理员可以修改权限级别
        if admin_level > 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "权限不足，只有0级和1级管理员可以修改权限级别"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40300,
                "message": "权限不足，只有0级和1级管理员可以修改权限级别"
            }), 403

        # 2. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "请求格式错误，需要JSON格式"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40000,
                "message": "请求格式错误，需要JSON格式"
            }), 400

        data = request.get_json()
        
        # 获取参数
        target_admin_id = data.get('target_admin_id')
        new_level = data.get('new_level')
        current_admin_password = data.get('current_admin_password')
        
        # 验证基本字段
        if not all([target_admin_id, new_level, current_admin_password]):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "缺少必要字段: target_admin_id, new_level, current_admin_password"
            }), 400
        
        # 验证新权限级别
        if not isinstance(new_level, int) or new_level < 0 or new_level > 3:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "新权限级别必须为0-3的整数", "new_level": new_level},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "新权限级别必须为0-3的整数（0为超级管理员，1为高级管理员，2为普通管理员，3为初级管理员）"
            }), 400
        
        # 3. 验证当前管理员密码
        current_admin = Admin.query.get(admin_id)
        if not current_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "当前管理员不存在"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40400,
                "message": "当前管理员不存在"
            }), 404
        
        if not bcrypt.checkpw(current_admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "当前管理员密码验证失败"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40100,
                "message": "当前管理员密码验证失败"
            }), 401
        
        # 4. 获取目标管理员信息
        target_admin = Admin.query.get(target_admin_id)
        if not target_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "目标管理员不存在", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40400,
                "message": "目标管理员不存在"
            }), 404
        
        # 5. 不能修改ID为1的超级管理员权限
        if target_admin.admin_id == 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "不能修改超级管理员的权限", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "不能修改超级管理员的权限"
            }), 403
        
        # 6. 检查是否尝试自己修改自己的权限
        if target_admin_id == admin_id:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "不能修改自己的权限级别", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "不能修改自己的权限级别"
            }), 403
        
        # 7. 特殊规则：只有0级管理员能修改为0级管理员
        if new_level == 0 and current_admin.admin_level != 0:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "权限不足，只有0级管理员可以设置0级管理员", "current_level": current_admin.admin_level},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "权限不足，只有0级管理员可以设置0级管理员"
            }), 403
            
        # 8. 特殊规则：检查是否已存在0级管理员（如果尝试设置新的0级管理员）
        if new_level == 0 and target_admin.admin_level != 0:
            # 检查是否已存在0级管理员（除了目标管理员外）
            level_0_admin_exists = Admin.query.filter(Admin.admin_level == 0, Admin.admin_id != target_admin_id).first() is not None
            if level_0_admin_exists:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="change_authority",
                    details={"error": "已存在0级管理员，不能创建新的0级管理员"},
                    status="failed",
                    resource_type="admins",
                    resource_id=target_admin_id
                )
                return jsonify({
                    "code": 40300,
                    "message": "已存在0级管理员，不能创建新的0级管理员"
                }), 403
        
        # 9. 特殊规则：1级管理员不能修改1级管理员的权限
        if current_admin.admin_level == 1 and target_admin.admin_level == 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_authority",
                details={"error": "权限不足，1级管理员不能修改1级管理员的权限"},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "权限不足，1级管理员不能修改1级管理员的权限"
            }), 403
            
        # 10. 保存当前权限级别用于日志记录
        previous_level = target_admin.admin_level
        
        # 8. 如果权限级别没有变化，直接返回成功
        if previous_level == new_level:
            return jsonify({
                "code": 0,
                "message": "权限级别未变化",
                "data": {
                    "admin_id": target_admin.admin_id,
                    "admin_name": target_admin.admin_name,
                    "previous_level": previous_level,
                    "new_level": new_level
                }
            }), 200
        
        # 9. 执行权限级别修改
        target_admin.admin_level = new_level
        db.session.commit()
        
        # 10. 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="change_authority",
            details={
                "target_admin_id": target_admin.admin_id,
                "target_admin_name": target_admin.admin_name,
                "previous_level": previous_level,
                "new_level": new_level
            },
            status="success",
            resource_type="admins",
            resource_id=target_admin_id
        )
        
        # 11. 记录MongoDB日志
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin_id,
                "admin_name": current_admin.admin_name,
                "operation": "change_authority",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "status": "success",
                "details": {
                    "target_admin_id": target_admin.admin_id,
                    "target_admin_name": target_admin.admin_name,
                    "previous_level": previous_level,
                    "new_level": new_level
                }
            })
        
        # 12. 返回成功响应
        return jsonify({
            "code": 0,
            "message": "修改管理员权限成功",
            "data": {
                "admin_id": target_admin.admin_id,
                "admin_name": target_admin.admin_name,
                "previous_level": previous_level,
                "new_level": new_level
            }
        }), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] 修改管理员权限异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="change_authority",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=target_admin_id if 'target_admin_id' in locals() else None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/devices/status', methods=['GET'])
@admin_required
def get_device_status(admin_id, admin_level):
    """
    获取设备状态统计接口
    请求示例：/api/v1/admin/devices/status
    
    返回格式：
    {
        "code": 0,
        "message": "获取设备状态统计成功",
        "data": {
            "inactive": 未激活设备数量,
            "online": 在线设备数量,
            "offline": 离线设备数量,
            "total": 设备总数
        }
    }
    """
    try:
        # 从MySQL获取所有设备列表
        devices = Device.query.all()
        
        # 获取所有设备ID列表
        device_ids = [device.device_id for device in devices]
        
        # 初始化计数器
        inactive_count = 0
        online_count = 0
        offline_count = 0
        
        # 统计未激活设备数量
        for device in devices:
            if not device.is_activated:
                inactive_count += 1
        
        # 从MongoDB获取最新设备状态
        online_device_ids = set()
        with mongo_collection(Config.MONGODB_COLLECTIONS["device_status"]) as collection:
            # 获取每个设备的最新状态记录
            pipeline = [
                {"$match": {"device_id": {"$in": device_ids}}},
                {"$sort": {"timestamp": -1}},
                {"$group": {
                    "_id": "$device_id",
                    "latest_status": {"$first": "$$ROOT"}
                }},
                {"$replaceRoot": {"newRoot": "$latest_status"}}
            ]
            
            latest_statuses = list(collection.aggregate(pipeline))
            
            # 根据MongoDB中的状态统计在线设备
            for status in latest_statuses:
                # 只处理已激活的设备 (未激活设备已在前面统计)
                device = next((d for d in devices if d.device_id == status["device_id"] and d.is_activated), None)
                if device:
                    # 设备在线条件: power.state 为 "ON" 且 connection_status 为 "ONLINE"
                    if status.get("power", {}).get("state") == "ON" and status.get("connection_status") == "ONLINE":
                        online_count += 1
                        online_device_ids.add(status["device_id"])
        
        # 计算离线设备数量 (已激活但不在线的设备)
        activated_count = sum(1 for device in devices if device.is_activated)
        offline_count = activated_count - online_count
        
        # 构建返回数据
        status_stats = {
            "inactive": inactive_count,
            "online": online_count,
            "offline": offline_count,
            "total": len(devices)
        }
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="get_device_status_stats",
            details={},
            status="success",
            resource_type="devices",
            resource_id=None
        )
        
        return jsonify({
            "code": 0,
            "message": "获取设备状态统计成功",
            "data": status_stats
        }), 200
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取设备状态统计异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="get_device_status_stats",
            details={"error": str(e)},
            status="failed",
            resource_type="devices",
            resource_id=None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/toggle_active', methods=['POST'])
@admin_required
def toggle_admin_active(admin_id, admin_level):
    """
    禁用或解禁管理员账号接口，仅限1级管理员使用
    请求示例：
    {
        "target_admin_id": 3,  # 要修改的管理员ID
        "is_active": false,  # 设置的状态(true解禁, false禁用)
        "current_admin_password": "password123"  # 当前管理员密码(验证身份)
    }
    
    返回格式：
    {
        "code": 0,
        "message": "修改管理员状态成功",
        "data": {
            "admin_id": 3,
            "admin_name": "管理员名称",
            "previous_state": true,
            "new_state": false,
            "operation": "ban" or "unban"
        }
    }
    """
    try:
        # 1. 检查当前管理员权限级别
        if admin_level >= 2:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "权限不足，只有1级管理员可以禁用/解禁账号"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40300,
                "message": "权限不足，只有1级管理员可以禁用/解禁账号"
            }), 403

        # 2. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "请求格式错误，需要JSON格式"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40000,
                "message": "请求格式错误，需要JSON格式"
            }), 400

        data = request.get_json()
        
        # 获取参数
        target_admin_id = data.get('target_admin_id')
        is_active = data.get('is_active')
        current_admin_password = data.get('current_admin_password')
        
        # 验证基本字段
        if target_admin_id is None or is_active is None or not current_admin_password:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "缺少必要字段: target_admin_id, is_active, current_admin_password"
            }), 400
        
        # 验证is_active为布尔值
        if not isinstance(is_active, bool):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "is_active必须是布尔值", "is_active": is_active},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "is_active必须是布尔值(true/false)"
            }), 400
        
        # 3. 验证当前管理员密码
        current_admin = Admin.query.get(admin_id)
        if not current_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "当前管理员不存在"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40400,
                "message": "当前管理员不存在"
            }), 404
        
        if not bcrypt.checkpw(current_admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "当前管理员密码验证失败"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40100,
                "message": "当前管理员密码验证失败"
            }), 401
        
        # 4. 获取目标管理员信息
        target_admin = Admin.query.get(target_admin_id)
        if not target_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "目标管理员不存在", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40400,
                "message": "目标管理员不存在"
            }), 404
        
        # 5. 不能修改ID为1的超级管理员状态
        if target_admin.admin_id == 1:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "不能修改超级管理员的状态", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "不能修改超级管理员的状态"
            }), 403
        
        # 6. 检查是否尝试自己修改自己的状态
        if target_admin_id == admin_id:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="toggle_admin_active",
                details={"error": "不能修改自己的账号状态", "target_admin_id": target_admin_id},
                status="failed",
                resource_type="admins",
                resource_id=target_admin_id
            )
            return jsonify({
                "code": 40300,
                "message": "不能修改自己的账号状态"
            }), 403
        
        # 7. 保存当前状态用于日志记录
        previous_state = target_admin.is_active
        
        # 8. 如果状态没有变化，直接返回成功
        if previous_state == is_active:
            return jsonify({
                "code": 0,
                "message": "账号状态未变化",
                "data": {
                    "admin_id": target_admin.admin_id,
                    "admin_name": target_admin.admin_name,
                    "previous_state": previous_state,
                    "new_state": is_active,
                    "operation": "unban" if is_active else "ban"
                }
            }), 200
        
        # 9. 执行状态修改
        target_admin.is_active = is_active
        db.session.commit()
        
        # 确定操作类型
        operation_type = "unban" if is_active else "ban"
        
        # 10. 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation=f"{operation_type}_admin",
            details={
                "target_admin_id": target_admin.admin_id,
                "target_admin_name": target_admin.admin_name,
                "previous_state": previous_state,
                "new_state": is_active
            },
            status="success",
            resource_type="admins",
            resource_id=target_admin_id
        )
        
        # 11. 记录MongoDB日志
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin_id,
                "admin_name": current_admin.admin_name,
                "operation": f"{operation_type}_admin",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "status": "success",
                "details": {
                    "target_admin_id": target_admin.admin_id,
                    "target_admin_name": target_admin.admin_name,
                    "previous_state": previous_state,
                    "new_state": is_active
                }
            })
        
        # 12. 返回成功响应
        return jsonify({
            "code": 0,
            "message": f"{'解禁' if is_active else '禁用'}管理员成功",
            "data": {
                "admin_id": target_admin.admin_id,
                "admin_name": target_admin.admin_name,
                "previous_state": previous_state,
                "new_state": is_active,
                "operation": operation_type
            }
        }), 200
        
    except Exception as e:
        # 回滚数据库事务
        db.session.rollback()
        
        # 记录错误日志
        print(f"[SYSTEM ERROR] {'解禁' if is_active else '禁用'}管理员异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="toggle_admin_active",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=target_admin_id if 'target_admin_id' in locals() else None
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500

@admin_bp.route('/v1/admin/change_name', methods=['POST'])
@admin_required
def change_admin_name(admin_id, admin_level):
    """
    修改当前管理员的账户名接口
    请求示例：
    {
        "new_admin_name": "new_username",   # 新的管理员用户名
        "admin_password": "password123"     # 当前管理员密码(验证身份)
    }
    
    返回格式：
    {
        "code": 0,
        "message": "账户名修改成功",
        "data": {
            "admin_id": 1,
            "previous_name": "old_username",
            "new_name": "new_username"
        }
    }
    """
    try:
        # 1. 获取并校验请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_admin_name",
                details={"error": "请求格式错误，需要JSON格式"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40000,
                "message": "请求格式错误，需要JSON格式"
            }), 400

        data = request.get_json()
        
        # 获取参数
        new_admin_name = data.get('new_admin_name')
        admin_password = data.get('admin_password')
        
        # 验证基本字段
        if not new_admin_name or not admin_password:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_admin_name",
                details={"error": "缺少必要字段"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40010,
                "message": "缺少必要字段: new_admin_name, admin_password"
            }), 400
        
        # 2. 检查新用户名是否已存在
        existing_admin = Admin.query.filter_by(admin_name=new_admin_name).first()
        if existing_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_admin_name",
                details={"error": "用户名已存在", "new_admin_name": new_admin_name},
                status="failed",
                resource_type="admins",
                resource_id=admin_id
            )
            return jsonify({
                "code": 40900,
                "message": "用户名已存在，请选择其他用户名"
            }), 409
            
        # 3. 获取当前管理员并验证密码
        current_admin = Admin.query.get(admin_id)
        if not current_admin:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_admin_name",
                details={"error": "当前管理员不存在"},
                status="failed",
                resource_type="admins",
                resource_id=None
            )
            return jsonify({
                "code": 40400,
                "message": "当前管理员不存在"
            }), 404
        
        if not bcrypt.checkpw(admin_password.encode('utf-8'), current_admin.admin_key.encode('utf-8')):
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="change_admin_name",
                details={"error": "密码验证失败"},
                status="failed",
                resource_type="admins",
                resource_id=admin_id
            )
            return jsonify({
                "code": 40100,
                "message": "密码验证失败"
            }), 401
        
        # 4. 记录旧用户名，用于返回
        previous_name = current_admin.admin_name
        
        # 5. 更新管理员用户名
        current_admin.admin_name = new_admin_name
        db.session.commit()
        
        # 6. 记录操作日志到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one({
                "admin_id": admin_id,
                "admin_name": new_admin_name,
                "operation": "change_admin_name",
                "timestamp": datetime.now(),
                "ip": get_client_ip(),
                "status": "success",
                "details": {
                    "previous_name": previous_name,
                    "new_name": new_admin_name
                }
            })
        
        # 记录操作成功
        log_admin_operation(
            admin_id=admin_id,
            operation="change_admin_name",
            details={
                "previous_name": previous_name,
                "new_name": new_admin_name
            },
            status="success",
            resource_type="admins",
            resource_id=admin_id
        )
        
        return jsonify({
            "code": 0,
            "message": "账户名修改成功",
            "data": {
                "admin_id": admin_id,
                "previous_name": previous_name,
                "new_name": new_admin_name
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        print(f"[SYSTEM ERROR] 修改管理员账户名异常: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="change_admin_name",
            details={"error": str(e)},
            status="failed",
            resource_type="admins",
            resource_id=admin_id
        )
        
        return jsonify({
            "code": 50000,
            "message": "系统繁忙，请稍后重试",
            "error": str(e)
        }), 500
